guides/latest-model/gpt-5.2.md +0 −1079 deleted
File Deleted View Diff
1# Using GPT-5.2
2
3> For the complete documentation index, see [llms.txt](/llms.txt). Markdown versions of documentation pages are available by appending `.md` to the page URL.
4
5## Introduction
6
7GPT-5.2 was released as a flagship general-purpose model for both general and agentic tasks. Compared with GPT-5.1, it improved:
8
9- General intelligence
10- Instruction following
11- Accuracy and token efficiency
12- Multimodality—especially vision
13- Code generation—especially front-end UI creation
14- Tool calling and context management in the API
15- Spreadsheet understanding and creation
16
17Unlike the previous GPT-5.1 model, GPT-5.2 has new features for managing what the model "knows" and "remembers" to improve accuracy.
18
19This guide covers key features of the GPT-5 model family and how to get the most out of GPT-5.2.
20
21## Explore coding examples
22
23Click through a few demo applications generated entirely with a single prompt, without writing any code by hand. Note that these examples were either generated by GPT-5.2 or our previous flagship model, GPT-5.
24
25## Model, API, and feature updates
26
27The GPT-5.2 generation includes `gpt-5.2` for complex tasks that require broad world knowledge, `gpt-5.2-chat-latest` for ChatGPT-aligned behavior, and `gpt-5.2-pro` for problems that benefit from more compute.
28
29For a smaller model, use `gpt-5-mini`.
30
31To help you pick the model that best fits your use case, consider these tradeoffs:
32
33| Variant | Best for |
34| ------------------------------------------------- | ------------------------------------------------------------------------------------ |
35| [`gpt-5.2`](https://developers.openai.com/api/docs/models/gpt-5.2) | Complex reasoning, broad world knowledge, and code-heavy or multi-step agentic tasks |
36| [`gpt-5.2-pro`](https://developers.openai.com/api/docs/models/gpt-5.2-pro) | Tough problems that may take longer to solve but require harder thinking |
37| [`gpt-5.2-codex`](https://developers.openai.com/api/docs/models/gpt-5.2-codex) | Companies building interactive coding products; full spectrum of coding tasks |
38| [`gpt-5-mini`](https://developers.openai.com/api/docs/models/gpt-5-mini) | Cost-optimized reasoning and chat; balances speed, cost, and capability |
39| [`gpt-5-nano`](https://developers.openai.com/api/docs/models/gpt-5-nano) | High-throughput tasks, especially focused instruction-following or classification |
40
41### New features in GPT-5.2
42
43Just like GPT-5.1, the new GPT-5.2 has API features like custom tools, parameters to control verbosity and reasoning, and an allowed tools list. What's new in 5.2 is a new `xhigh` reasoning effort level, concise reasoning summaries, and new context management using _compaction_.
44
45This guide walks through some of the key features of the GPT-5 model family and how to get the most out of 5.2 in particular.
46
47For coding tasks, GPT-5.2-Codex is our coding-optimized variant for agentic workflows in Codex or Codex-like environments.
48
49### Lower reasoning effort
50
51The `reasoning.effort` parameter controls how many reasoning tokens the model generates before producing a response. Earlier reasoning models like o3 supported only `low`, `medium`, and `high`: `low` favored speed and fewer tokens, while `high` favored more thorough reasoning.
52
53With GPT-5.2, the lowest setting is `none` to provide lower-latency interactions. This is the default setting in GPT-5.2. If you need more thinking, slowly increase to `medium` and experiment with results.
54
55With reasoning effort set to `none`, prompting is important. To improve the model's reasoning quality, even with the default settings, encourage it to “think” or outline its steps before answering.
56
57Reasoning effort set to none
58
59```javascript
60import OpenAI from "openai";
61const openai = new OpenAI();
62
63const response = await openai.responses.create({
64 model: "gpt-5.2",
65 input:
66 "Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
67 reasoning: {
68 effort: "none",
69 },
70});
71
72console.log(response);
73```
74
75```python
76from openai import OpenAI
77
78client = OpenAI()
79
80response = client.responses.create(
81 model="gpt-5.2",
82 input="Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
83 reasoning={"effort": "none"},
84)
85
86print(response)
87```
88
89```go
90package main
91
92import (
93 "context"
94 "fmt"
95
96 "github.com/openai/openai-go/v3"
97 "github.com/openai/openai-go/v3/responses"
98 "github.com/openai/openai-go/v3/shared"
99)
100
101func main() {
102 client := openai.NewClient()
103 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
104 Model: "gpt-5.2",
105 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?")},
106 Reasoning: shared.ReasoningParam{Effort: shared.ReasoningEffortNone},
107 })
108 if err != nil {
109 panic(err)
110 }
111 fmt.Println(response)
112}
113```
114
115```java
116import com.openai.client.OpenAIClient;
117import com.openai.client.okhttp.OpenAIOkHttpClient;
118import com.openai.models.Reasoning;
119import com.openai.models.ReasoningEffort;
120import com.openai.models.responses.ResponseCreateParams;
121
122ResponseCreateParams params =
123 ResponseCreateParams.builder()
124 .model("gpt-5.2")
125 .input("Explain the bug and propose a fix.")
126 .reasoning(Reasoning.builder().effort(ReasoningEffort.NONE).build())
127 .build();
128
129client.responses().create(params).output().stream()
130 .flatMap(item -> item.message().stream())
131 .flatMap(message -> message.content().stream())
132 .flatMap(content -> content.outputText().stream())
133 .forEach(text -> System.out.println(text.text()));
134```
135
136```csharp
137using OpenAI.Responses;
138#pragma warning disable OPENAI001
139
140string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
141ResponsesClient client = new(key);
142
143CreateResponseOptions options = new()
144{
145 Model = "gpt-5.2",
146 ReasoningOptions = new ResponseReasoningOptions
147 {
148 ReasoningEffortLevel = ResponseReasoningEffortLevel.None,
149 },
150};
151options.InputItems.Add(
152 ResponseItem.CreateUserMessageItem(
153 "Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
154 )
155);
156
157ResponseResult response = await client.CreateResponseAsync(options);
158Console.WriteLine(response.GetOutputText());
159```
160
161```ruby
162require "openai"
163
164client = OpenAI::Client.new
165response = client.responses.create(
166 model: "gpt-5.2",
167 reasoning: { effort: :minimal },
168 input: "Explain the bug and propose a fix."
169)
170puts(response.output_text)
171```
172
173```bash
174curl --request POST \
175 --url https://api.openai.com/v1/responses \
176 --header "Authorization: Bearer $OPENAI_API_KEY" \
177 --header 'Content-type: application/json' \
178 --data '{
179 "model": "gpt-5.2",
180 "input": "Think carefully and outline your steps before answering. How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
181 "reasoning": {
182 "effort": "none"
183 }
184}'
185```
186
187
188### Verbosity
189
190Verbosity determines how many output tokens are generated. Lowering the number of tokens reduces overall latency. While the model's reasoning approach stays mostly the same, the model finds ways to answer more concisely—which can either improve or diminish answer quality, depending on your use case. Here are some scenarios for both ends of the verbosity spectrum:
191
192- **High verbosity:** Use when you need the model to provide thorough explanations of documents or perform extensive code refactoring.
193- **Low verbosity:** Best for situations where you want concise answers or focused code generation, such as SQL queries.
194
195GPT-5 made this option configurable as one of `high`, `medium`, or `low`. With GPT-5.2, verbosity remains configurable and defaults to `medium`.
196
197When generating code with GPT-5.2, `medium` and `high` verbosity levels yield longer, more structured code with inline explanations, while `low` verbosity produces shorter, more concise code with minimal commentary.
198
199Control verbosity
200
201```javascript
202import OpenAI from "openai";
203const openai = new OpenAI();
204
205const response = await openai.responses.create({
206 model: "gpt-5.2",
207 input:
208 "What is the answer to the ultimate question of life, the universe, and everything?",
209 text: {
210 verbosity: "low",
211 },
212});
213
214console.log(response);
215```
216
217```python
218from openai import OpenAI
219
220client = OpenAI()
221
222response = client.responses.create(
223 model="gpt-5.2",
224 input="What is the answer to the ultimate question of life, the universe, and everything?",
225 text={"verbosity": "low"},
226)
227
228print(response)
229```
230
231```go
232package main
233
234import (
235 "context"
236 "fmt"
237
238 "github.com/openai/openai-go/v3"
239 "github.com/openai/openai-go/v3/responses"
240)
241
242func main() {
243 client := openai.NewClient()
244 response, err := client.Responses.New(context.Background(), responses.ResponseNewParams{
245 Model: "gpt-5.2",
246 Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("What is the answer to the ultimate question of life, the universe, and everything?")},
247 Text: responses.ResponseTextConfigParam{Verbosity: responses.ResponseTextConfigVerbosityLow},
248 })
249 if err != nil {
250 panic(err)
251 }
252 fmt.Println(response)
253}
254```
255
256```java
257import com.openai.client.OpenAIClient;
258import com.openai.client.okhttp.OpenAIOkHttpClient;
259import com.openai.models.responses.ResponseCreateParams;
260import com.openai.models.responses.ResponseTextConfig;
261
262ResponseCreateParams params =
263 ResponseCreateParams.builder()
264 .model("gpt-5.2")
265 .input("Explain the bug and propose a fix.")
266 .text(ResponseTextConfig.builder().verbosity(ResponseTextConfig.Verbosity.LOW).build())
267 .build();
268
269client.responses().create(params).output().stream()
270 .flatMap(item -> item.message().stream())
271 .flatMap(message -> message.content().stream())
272 .flatMap(content -> content.outputText().stream())
273 .forEach(text -> System.out.println(text.text()));
274```
275
276```ruby
277require "openai"
278
279client = OpenAI::Client.new
280response = client.responses.create(
281 model: "gpt-5.2",
282 text: { verbosity: :low },
283 input: "Explain the bug and propose a fix."
284)
285puts(response.output_text)
286```
287
288```bash
289curl --request POST \
290 --url https://api.openai.com/v1/responses \
291 --header "Authorization: Bearer $OPENAI_API_KEY" \
292 --header 'Content-type: application/json' \
293 --data '{
294 "model": "gpt-5.2",
295 "input": "What is the answer to the ultimate question of life, the universe, and everything?",
296 "text": {
297 "verbosity": "low"
298 }
299}'
300```
301
302
303You can still steer verbosity through prompting after setting it to `low` in the API. The verbosity parameter defines a general token range at the system prompt level, but the actual output is flexible to both developer and user prompts within that range.
304
305### Using tools with GPT-5.2
306
307GPT-5.2 has been post-trained on specific tools. See the [tools docs](https://developers.openai.com/api/docs/guides/tools) for more specific guidance.
308
309#### The apply patch tool
310
311The `apply_patch` tool lets GPT-5.2 create, update, and delete files in your codebase using structured diffs. Instead of just suggesting edits, the model emits patch operations that your application applies and then reports back on, enabling iterative, multi-step code editing workflows. [Read the docs](https://developers.openai.com/api/docs/guides/tools-apply-patch).
312
313Under the hood, this implementation uses a freeform function call rather than a JSON format. In testing, the named function decreased `apply_patch` failure rates by 35%.
314
315#### Shell tool
316
317Local shell is supported in GPT-5.2. The shell tool allows the model to interact with your local computer through a controlled command-line interface. [Read the docs](https://developers.openai.com/api/docs/guides/tools-shell) to learn more.
318
319### Custom tools
320
321When the GPT-5 model family launched, we introduced a new capability called custom tools, which lets models send any raw text as tool call input but still constrain outputs if desired. This tool behavior remains true in GPT-5.2.
322
323[Function calling guide
324
325
326
327 Learn about custom tools in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)
328
329#### Freeform inputs
330
331Define your tool with `type: custom` to enable models to send plaintext inputs directly to your tools, rather than being limited to structured JSON. The model can send any raw text—code, SQL queries, shell commands, configuration files, or long-form prose—directly to your tool.
332
333```json
334{
335 "type": "custom",
336 "name": "code_exec",
337 "description": "Executes arbitrary python code"
338}
339```
340
341#### Constraining outputs
342
343GPT-5.2 supports context-free grammars (`CFGs`) for custom tools, letting you provide a Lark grammar to constrain outputs to a specific syntax or DSL. Attaching a CFG, for example a SQL or DSL grammar, ensures the assistant's text matches your grammar.
344
345This enables precise, constrained tool calls or structured responses and lets you enforce strict syntactic or domain-specific formats directly in GPT-5.2's function calling, improving control and reliability for complex or constrained domains.
346
347#### Best practices for custom tools
348
349- **Write concise, explicit tool descriptions.** The model chooses what to send based on your description; state explicitly if you want it to always call the tool.
350- **Validate outputs on the server side**. Freeform strings are powerful but require safeguards against injection or unsafe commands.
351
352### Allowed tools
353
354The `allowed_tools` parameter under `tool_choice` lets you pass N tool definitions but restrict the model to only M (< N) of them. List your full toolkit in `tools`, and then use an `allowed_tools` block to name the subset and specify a mode—either `auto` (the model may pick any of those) or `required` (the model must invoke one).
355
356[Function calling guide
357
358
359
360 Learn about the allowed tools option in the function calling guide.](https://developers.openai.com/api/docs/guides/function-calling)
361
362By separating all possible tools from the subset that can be used _now_, you gain greater safety, predictability, and improved prompt caching. You also avoid brittle prompt engineering, such as hard-coded call order. GPT-5.2 dynamically invokes or requires specific functions mid-conversation while reducing the risk of unintended tool usage over long contexts.
363
364| | **Standard Tools** | **Allowed Tools** |
365| ---------------- | ----------------------------------------- | ------------------------------------------------------------- |
366| Model's universe | All tools listed under **`"tools": […]`** | Only the subset under **`"tools": […]`** in **`tool_choice`** |
367| Tool invocation | Model may or may not call any tool | Model restricted to (or required to call) chosen tools |
368| Purpose | Declare available capabilities | Constrain which capabilities are actually used |
369
370```json
371{
372 "tool_choice": {
373 "type": "allowed_tools",
374 "mode": "auto",
375 "tools": [
376 { "type": "function", "name": "get_weather" },
377 { "type": "function", "name": "search_docs" }
378 ]
379 }
380}
381```
382
383For a more detailed overview of all of these new features, see the [accompanying cookbook](https://developers.openai.com/cookbook/examples/gpt-5/gpt-5-2_prompting_guide).
384
385### Preambles
386
387Preambles are brief, user-visible explanations that GPT-5.2 generates before invoking any tool or function, outlining its intent or plan—for example, “why I'm calling this tool.” They appear after the chain of thought and before the actual tool call, making the model's reasoning easier to understand and debug while supporting precise steering.
388
389By letting GPT-5.2 “think out loud” before each tool call, preambles boost tool-calling accuracy (and overall task success) without bloating reasoning overhead. To enable preambles, add a system or developer instruction—for example: “Before you call a tool, explain why you are calling it.” GPT-5.2 adds a concise rationale to each specified tool call. The model may also output multiple messages between tool calls, which can enhance the interaction experience—particularly for minimal reasoning or latency-sensitive use cases.
390
391For more on using preambles, see the [GPT-5 prompting cookbook](https://developers.openai.com/cookbook/examples/gpt-5/gpt-5_prompting_guide#tool-preambles).
392
393## Migration quickstart
394
395GPT-5.2 works best with the Responses API, which supports preserving reasoning context between turns. Read below to migrate from your current model or API.
396
397### Migrating from other models to GPT-5.2
398
399While the model should be close to a drop-in replacement for GPT-5.1, there are a few key changes to call out. See the [GPT-5.2 prompting guide](https://developers.openai.com/cookbook/examples/gpt-5/gpt-5-2_prompting_guide) for specific updates to make in your prompts.
400
401Using GPT-5 models with the Responses API provides improved intelligence because of the API design. The Responses API can pass the previous turn's CoT to the model. This leads to fewer generated reasoning tokens, higher cache hit rates, and less latency. To learn more, see an [in-depth guide](https://developers.openai.com/cookbook/examples/responses_api/reasoning_items) on the benefits of the Responses API.
402
403When migrating to GPT-5.2 from an older OpenAI model, start by experimenting with reasoning levels and prompting strategies. Based on our testing, we recommend using our [prompt optimizer](https://platform.openai.com/chat/edit?models=gpt-5.2&optimize=true)—which automatically updates your prompts for GPT-5.2 based on our best practices—and following this model-specific guidance:
404
405- **`gpt-5.1`**: `gpt-5.2` with default settings is meant to be a drop-in replacement.
406- **o3**: `gpt-5.2` with `medium` or `high` reasoning. Start with `medium` reasoning with prompt tuning, then increase to `high` if you aren't getting the results you want.
407- **`gpt-4.1`**: `gpt-5.2` with `none` reasoning. Start with `none` and tune your prompts; increase if you need better performance.
408- **`o4-mini` or `gpt-4.1-mini`**: `gpt-5-mini` with prompt tuning is a great replacement.
409- **`gpt-4.1-nano`**: `gpt-5-nano` with prompt tuning is a great replacement.
410
411### GPT-5.2 parameter compatibility
412
413The following parameters are **only supported** when using GPT-5.2 with reasoning effort set to `none`:
414
415- `temperature`
416- `top_p`
417- `logprobs`
418
419Requests to GPT-5.2 or GPT-5.1 with any other reasoning effort setting, or to older GPT-5 models—for example, `gpt-5`, `gpt-5-mini`, or `gpt-5-nano`—that include these fields will raise an error.
420
421To achieve similar results with reasoning effort set higher, or with another GPT-5 family model, try these alternative parameters:
422
423- **Reasoning depth:** `reasoning: { effort: "none" | "low" | "medium" | "high" | "xhigh" }`
424- **Output verbosity:** `text: { verbosity: "low" | "medium" | "high" }`
425- **Output length:** `max_output_tokens`
426
427### Migrating from Chat Completions to Responses API
428
429The biggest difference, and main reason to migrate from Chat Completions to the Responses API for GPT-5.2, is support for passing chain of thought (CoT) between turns. See a full [comparison of the APIs](https://developers.openai.com/api/docs/guides/migrate-to-responses).
430
431Passing CoT exists only in the Responses API, and we've seen improved intelligence, fewer generated reasoning tokens, higher cache hit rates, and lower latency as a result of doing so. Most other parameters remain at parity, though the formatting is different. Here's how new parameters are handled differently between Chat Completions and the Responses API:
432
433**Reasoning effort**
434
435
436
437Responses API
438
439 Generate response with reasoning effort set to none
440
441```bash
442curl --request POST \
443 --url https://api.openai.com/v1/responses \
444 --header "Authorization: Bearer $OPENAI_API_KEY" \
445 --header "Content-type: application/json" \
446 --data '{
447 "model": "gpt-5.2",
448 "input": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
449 "reasoning": {
450 "effort": "none"
451 }
452}'
453```
454
455
456
457
458
459
460Chat Completions
461
462 Generate response with reasoning effort set to none
463
464```bash
465curl --request POST \
466 --url https://api.openai.com/v1/chat/completions \
467 --header "Authorization: Bearer $OPENAI_API_KEY" \
468 --header "Content-type: application/json" \
469 --data '{
470 "model": "gpt-5.2",
471 "messages": [
472 {
473 "role": "user",
474 "content": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
475 }
476 ],
477 "reasoning_effort": "none"
478}'
479```
480
481
482
483**Verbosity**
484
485
486
487Responses API
488
489 Control verbosity
490
491```bash
492curl --request POST \
493 --url https://api.openai.com/v1/responses \
494 --header "Authorization: Bearer $OPENAI_API_KEY" \
495 --header "Content-type: application/json" \
496 --data '{
497 "model": "gpt-5.2",
498 "input": "What is the answer to the ultimate question of life, the universe, and everything?",
499 "text": {
500 "verbosity": "low"
501 }
502}'
503```
504
505
506
507
508
509
510Chat Completions
511
512 Control verbosity
513
514```bash
515curl --request POST \
516 --url https://api.openai.com/v1/chat/completions \
517 --header "Authorization: Bearer $OPENAI_API_KEY" \
518 --header "Content-type: application/json" \
519 --data '{
520 "model": "gpt-5.2",
521 "messages": [
522 {
523 "role": "user",
524 "content": "What is the answer to the ultimate question of life, the universe, and everything?"
525 }
526 ],
527 "verbosity": "low"
528}'
529```
530
531
532
533**Custom tools**
534
535
536
537Responses API
538
539 Custom tool call
540
541```bash
542curl --request POST \
543 --url https://api.openai.com/v1/responses \
544 --header "Authorization: Bearer $OPENAI_API_KEY" \
545 --header "Content-type: application/json" \
546 --data '{
547 "model": "gpt-5.2",
548 "input": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry",
549 "tools": [
550 {
551 "type": "custom",
552 "name": "code_exec",
553 "description": "Executes arbitrary Python code"
554 }
555 ]
556}'
557```
558
559
560
561
562
563
564Chat Completions
565
566 Custom tool call
567
568```bash
569curl --request POST \
570 --url https://api.openai.com/v1/chat/completions \
571 --header "Authorization: Bearer $OPENAI_API_KEY" \
572 --header "Content-type: application/json" \
573 --data '{
574 "model": "gpt-5.2",
575 "messages": [
576 {
577 "role": "user",
578 "content": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry"
579 }
580 ],
581 "tools": [
582 {
583 "type": "custom",
584 "custom": {
585 "name": "code_exec",
586 "description": "Executes arbitrary Python code"
587 }
588 }
589 ]
590}'
591```
592
593
594
595
596## Prompting best practices
597
598### 2. Key behavioral differences
599
600**Compared with previous generation models (e.g. GPT-5 and GPT-5.1), GPT-5.2 delivers:**
601
602- **More deliberate scaffolding:** Builds clearer plans and intermediate structure by default; benefits from explicit scope and verbosity constraints.
603- **Generally lower verbosity:** More concise and task-focused, though still prompt-sensitive and preference needs to be articulated in the prompt.
604- **Stronger instruction adherence:** Less drift from user intent; improved formatting and rationale presentation.
605- **Tool efficiency trade-offs:** Takes additional tool actions in interactive flows compared with GPT-5.1, can be further optimized via prompting.
606- **Conservative grounding bias:** Tends to favor correctness and explicit reasoning; ambiguity handling improves with clarification prompts.
607
608This guide focuses on prompting GPT-5.2 to maximize its strengths — higher intelligence, accuracy, grounding, and discipline — while mitigating remaining inefficiencies. Existing GPT-5 / GPT-5.1 prompting guidance largely carries over and remains applicable.
609
610### 3. Prompting patterns
611
612Adapt following themes into your prompts for better steer on GPT-5.2
613
614#### 3.1 Controlling verbosity and output shape
615
616Give **clear and concrete length constraints** especially in enterprise and coding agents.
617
618Example clamp adjust based on desired verbosity:
619
620```text
621<output_verbosity_spec>
622- Default: 3–6 sentences or ≤5 bullets for typical answers.
623- For simple “yes/no + short explanation” questions: ≤2 sentences.
624- For complex multi-step or multi-file tasks:
625 - 1 short overview paragraph
626 - then ≤5 bullets tagged: What changed, Where, Risks, Next steps, Open questions.
627- Provide clear and structured responses that balance informativeness with conciseness. Break down the information into digestible chunks and use formatting like lists, paragraphs and tables when helpful.
628- Avoid long narrative paragraphs; prefer compact bullets and short sections.
629- Do not rephrase the user’s request unless it changes semantics.
630</output_verbosity_spec>
631```
632
633#### 3.2 Preventing Scope drift (e.g., UX / design in frontend tasks)
634
635GPT-5.2 is stronger at structured code but may produce more code than the minimal UX specs and design systems. To stay within the scope, explicitly forbid extra features and uncontrolled styling.
636
637```text
638<design_and_scope_constraints>
639- Explore any existing design systems and understand it deeply.
640- Implement EXACTLY and ONLY what the user requests.
641- No extra features, no added components, no UX embellishments.
642- Style aligned to the design system at hand.
643- Do NOT invent colors, shadows, tokens, animations, or new UI elements, unless requested or necessary to the requirements.
644- If any instruction is ambiguous, choose the simplest valid interpretation.
645</design_and_scope_constraints>
646```
647
648For design system enforcement, reuse your 5.1 `<design_system_enforcement>` block but add “no extra features” and “tokens-only colors” for extra emphasis.
649
650#### 3.3 Long-context and recall
651
652For long-context tasks, the prompt may benefit from **force summarization and re-grounding**. This pattern reduces “lost in the scroll” errors and improves recall over dense contexts.
653
654```text
655<long_context_handling>
656- For inputs longer than ~10k tokens (multi-chapter docs, long threads, multiple PDFs):
657 - First, produce a short internal outline of the key sections relevant to the user’s request.
658 - Re-state the user’s constraints explicitly (e.g., jurisdiction, date range, product, team) before answering.
659 - In your answer, anchor claims to sections (“In the ‘Data Retention’ section…”) rather than speaking generically.
660- If the answer depends on fine details (dates, thresholds, clauses), quote or paraphrase them.
661</long_context_handling>
662```
663
664#### 3.4 Handling ambiguity & hallucination risk
665
666Configure the prompt for overconfident hallucinations on ambiguous queries (e.g., unclear requirements, missing constraints, or questions that need fresh data but no tools are called).
667
668Mitigation prompt:
669
670```text
671<uncertainty_and_ambiguity>
672- If the question is ambiguous or underspecified, explicitly call this out and:
673 - Ask up to 1–3 precise clarifying questions, OR
674 - Present 2–3 plausible interpretations with clearly labeled assumptions.
675- When external facts may have changed recently (prices, releases, policies) and no tools are available:
676 - Answer in general terms and state that details may have changed.
677- Never fabricate exact figures, line numbers, or external references when you are uncertain.
678- When you are unsure, prefer language like “Based on the provided context…” instead of absolute claims.
679</uncertainty_and_ambiguity>
680```
681
682You can also add a short self-check step for high-risk outputs:
683
684```text
685<high_risk_self_check>
686Before finalizing an answer in legal, financial, compliance, or safety-sensitive contexts:
687- Briefly re-scan your own answer for:
688 - Unstated assumptions,
689 - Specific numbers or claims not grounded in context,
690 - Overly strong language (“always,” “guaranteed,” etc.).
691- If you find any, soften or qualify them and explicitly state assumptions.
692</high_risk_self_check>
693```
694
695### 4. Compaction (Extending Effective Context)
696
697For long-running, tool-heavy workflows that exceed the standard context window, GPT-5.2 with Reasoning supports response compaction via the /responses/compact endpoint. Compaction performs a loss-aware compression pass over prior conversation state, returning encrypted, opaque items that preserve task-relevant information while dramatically reducing token footprint. This allows the model to continue reasoning across extended workflows without hitting context limits.
698
699**When to use compaction**
700
701- Multi-step agent flows with many tool calls
702- Long conversations where earlier turns must be retained
703- Iterative reasoning beyond the maximum context window
704
705**Key properties**
706
707- Produces opaque, encrypted items (internal logic may evolve)
708- Designed for continuation, not inspection
709- Compatible with GPT-5.2 and Responses API
710- Safe to run repeatedly in long sessions
711
712**Compact a Response**
713
714Endpoint
715
716```text
717POST https://api.openai.com/v1/responses/compact
718```
719
720**What it does**
721
722Runs a compaction pass over a conversation and returns a compacted response object. Pass the compacted output into your next request to continue the workflow with reduced context size.
723
724**Best practices**
725
726- Monitor context usage and plan ahead to avoid hitting context window limits
727- Compact after major milestones (e.g., tool-heavy phases), not every turn
728- Keep prompts functionally identical when resuming to avoid behavior drift
729- Treat compacted items as opaque; don’t parse or depend on internals
730
731For guidance on when and how to compact in production, see the [Conversation State](https://developers.openai.com/api/docs/guides/conversation-state?api-mode=responses) guide and [Compact a Response](https://developers.openai.com/api/reference/resources/responses/methods/compact) page.
732
733Here is an example:
734
735```python
736from openai import OpenAI
737import json
738
739
740client = OpenAI()
741
742
743response = client.responses.create(
744 model="gpt-5.2",
745 input=[
746 {
747 "role": "user",
748 "content": "write a very long poem about a dog.",
749 },
750 ],
751)
752
753
754output_json = [msg.model_dump() for msg in response.output]
755
756
757# Now compact, passing the original user prompt and the assistant text as inputs
758compacted_response = client.responses.compact(
759 model="gpt-5.2",
760 input=[
761 {
762 "role": "user",
763 "content": "write a very long poem about a dog.",
764 },
765 output_json[0],
766 ],
767)
768
769
770print(json.dumps(compacted_response.model_dump(), indent=2))
771```
772
773```java
774import com.openai.client.OpenAIClient;
775import com.openai.client.okhttp.OpenAIOkHttpClient;
776import com.openai.core.JsonValue;
777import com.openai.models.responses.EasyInputMessage;
778import com.openai.models.responses.ResponseCompactParams;
779import com.openai.models.responses.ResponseCreateParams;
780import com.openai.models.responses.ResponseInputItem;
781import java.util.ArrayList;
782
783var input = new ArrayList<ResponseInputItem>();
784input.add(
785 ResponseInputItem.ofEasyInputMessage(
786 EasyInputMessage.builder()
787 .role(EasyInputMessage.Role.USER)
788 .content("Write a very long poem about a dog.")
789 .build()));
790var response =
791 client
792 .responses()
793 .create(ResponseCreateParams.builder().model("gpt-5.2").inputOfResponse(input).build());
794response.output().stream()
795 .map(item -> JsonValue.from(item).convert(ResponseInputItem.class))
796 .forEach(input::add);
797var compacted =
798 client
799 .responses()
800 .compact(
801 ResponseCompactParams.builder()
802 .model("gpt-5.2")
803 .inputOfResponseInputItems(input)
804 .build());
805System.out.println(compacted.output());
806```
807
808```ruby
809require "openai"
810
811client = OpenAI::Client.new
812response = client.responses.create(
813 model: "gpt-5.2",
814 input: [
815 {
816 role: :user,
817 content: "Write a very long poem about a dog."
818 }
819 ]
820)
821compaction = client.responses.compact(
822 model: "gpt-5.2",
823 input: [
824 {
825 role: :user,
826 content: "Write a very long poem about a dog."
827 },
828 *response.output
829 ]
830)
831
832puts(compaction.output)
833```
834
835
836### 5. Agentic steerability & user updates
837
838GPT-5.2 is strong on agentic scaffolding and multi-step execution when prompted well. You can reuse your GPT-5.1 `<user_updates_spec>` and `<solution_persistence>` blocks.
839
840Two key tweaks could be added to further push the performance of GPT-5.2:
841
842- Clamp verbosity of updates (shorter, more focused).
843- Make scope discipline explicit (don’t expand problem surface area).
844
845Example updated spec:
846
847```text
848<user_updates_spec>
849- Send brief updates (1–2 sentences) only when:
850 - You start a new major phase of work, or
851 - You discover something that changes the plan.
852- Avoid narrating routine tool calls (“reading file…”, “running tests…”).
853- Each update must include at least one concrete outcome (“Found X”, “Confirmed Y”, “Updated Z”).
854- Do not expand the task beyond what the user asked; if you notice new work, call it out as optional.
855</user_updates_spec>
856```
857
858### 6. Tool-calling and parallelism
859
860GPT-5.2 improves on 5.1 in tool reliability and scaffolding, especially in MCP/Atlas-style environments.
861Best practices as applicable to GPT-5 / 5.1:
862
863- Describe tools crisply: 1–2 sentences for what they do and when to use them.
864- Encourage parallelism explicitly for scanning codebases, vector stores, or multi-entity operations.
865- Require verification steps for high-impact operations (orders, billing, infra changes).
866
867Example tool usage section:
868
869```text
870<tool_usage_rules>
871- Prefer tools over internal knowledge whenever:
872 - You need fresh or user-specific data (tickets, orders, configs, logs).
873 - You reference specific IDs, URLs, or document titles.
874- Parallelize independent reads (read_file, fetch_record, search_docs) when possible to reduce latency.
875- After any write/update tool call, briefly restate:
876 - What changed,
877 - Where (ID or path),
878 - Any follow-up validation performed.
879</tool_usage_rules>
880```
881
882### 7. Structured extraction, PDF, and Office workflows
883
884This is an area where GPT-5.2 clearly shows strong improvements. To get the most out of it:
885
886- Always provide a schema or JSON shape for the output. You can use structured outputs for strict schema adherence.
887- Distinguish between required and optional fields.
888- Ask for “extraction completeness” and handle missing fields explicitly.
889
890Example:
891
892```text
893<extraction_spec>
894You will extract structured data from tables/PDFs/emails into JSON.
895
896- Always follow this schema exactly (no extra fields):
897 {
898 "party_name": string,
899 "jurisdiction": string | null,
900 "effective_date": string | null,
901 "termination_clause_summary": string | null
902 }
903- If a field is not present in the source, set it to null rather than guessing.
904- Before returning, quickly re-scan the source for any missed fields and correct omissions.
905</extraction_spec>
906```
907
908For multi-table/multi-file extraction, add guidance to:
909
910- Serialize per-document results separately.
911- Include a stable ID (filename, contract title, page range).
912
913### 8. Prompt Migration Guide to GPT-5.2
914
915This 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.
916
917Migration mapping
918Use the following default mappings when updating to GPT-5.2
919
920| Current model | Target model | Target reasoning_effort | Notes |
921| ------------- | ------------ | -------------------------------- | ----------------------------------------------------------------------------------------------------- |
922| GPT-4o | GPT-5.2 | none | Treat 4o/4.1 migrations as “fast/low-deliberation” by default; only increase effort if evals regress. |
923| GPT-4.1 | GPT-5.2 | none | Same mapping as GPT-4o to preserve snappy behavior. |
924| GPT-5 | GPT-5.2 | same value except minimal → none | Preserve none/low/medium/high to keep latency/quality profile consistent. |
925| GPT-5.1 | GPT-5.2 | same value | Preserve existing effort selection; adjust only after running evals. |
926
927\*Note that default reasoning level for GPT-5 is medium, and for GPT-5.1 and GPT-5.2 is none.
928
929We 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:
930
931- Step 1: Switch models, don’t change prompts yet. Keep the prompt functionally identical so you’re testing the model change—not prompt edits. Make one change at a time.
932- Step 2: Pin reasoning_effort. Explicitly set GPT-5.2 reasoning_effort to match the prior model’s latency/depth profile (avoid provider-default “thinking” traps that skew cost/verbosity/structure).
933- 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), you’re ready to ship.
934- Step 4: If regressions, tune the prompt. Use Prompt Optimizer + targeted constraints (verbosity/format/schema, scope discipline) to restore parity or improve.
935- Step 5: Re-run Evals after each small change. Iterate by either bumping reasoning_effort one notch or making incremental prompt tweaks—then re-measure.
936
937### 9. Web search and research
938
939GPT-5.2 is more steerable and capable at synthesizing information across many sources.
940
941Best practices to follow:
942
943- Specify the research bar up front: Tell the model how you want to perform search. Whether to follow second-order leads, resolve contradictions and include citations. Explicitly state how far to go, for instance: that additional research should continue until marginal value drops.
944
945- Constrain ambiguity by instruction, not questions: Instruct the model to cover all plausible intents comprehensively and not ask clarifying questions. Require breadth and depth when uncertainty exists.
946
947- Dictate output shape and tone: Set expectations for structure (Markdown, headers, tables for comparisons), clarity (define acronyms, concrete examples) and voice (conversational, persona-adaptive, non-sycophantic)
948
949```text
950<web_search_rules>
951- Act as an expert research assistant; default to comprehensive, well-structured answers.
952- Prefer web research over assumptions whenever facts may be uncertain or incomplete; include citations for all web-derived information.
953- Research all parts of the query, resolve contradictions, and follow important second-order implications until further research is unlikely to change the answer.
954- Do not ask clarifying questions; instead cover all plausible user intents with both breadth and depth.
955- Write clearly and directly using Markdown (headers, bullets, tables when helpful); define acronyms, use concrete examples, and keep a natural, conversational tone.
956</web_search_rules>
957```
958
959### 10. Conclusion
960
961GPT-5.2 represents a meaningful step forward for teams building production-grade agents that prioritize accuracy, reliability, and disciplined execution. It delivers stronger instruction following, cleaner output, and more consistent behavior across complex, tool-heavy workflows. Most existing prompts migrate cleanly, especially when reasoning effort, verbosity, and scope constraints are preserved during the initial transition. Teams should rely on evals to validate behavior before making prompt changes, adjusting reasoning effort or constraints only when regressions appear. With explicit prompting and measured iteration, GPT-5.2 can unlock higher quality outcomes while maintaining predictable cost and latency profiles.
962
963### Appendix
964
965#### Example prompt for a web research agent:
966
967```text
968You 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.
969############################################
970CORE MISSION
971############################################
972Answer the user’s question fully and helpfully, with enough evidence that a skeptical reader can trust it.
973Never invent facts. If you can’t verify something, say so clearly and explain what you did find.
974Default to being detailed and useful rather than short, unless the user explicitly asks for brevity.
975Go one step further: after answering the direct question, add high-value adjacent material that supports the user’s underlying goal without drifting off-topic. Don’t 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.
976############################################
977PERSONA
978############################################
979You are the world’s greatest research assistant.
980Engage warmly, enthusiastically, and honestly, while avoiding any ungrounded or sycophantic flattery.
981Adopt whatever persona the user asks you to take.
982Default tone: natural, conversational, and playful rather than formal or robotic, unless the subject matter requires seriousness.
983Match the vibe of the request: for casual conversation lean supportive; for work/task-focused requests lean straightforward and helpful.
984############################################
985FACTUALITY AND ACCURACY (NON-NEGOTIABLE)
986############################################
987You MUST browse the web and include citations for all non-creative queries, unless:
988The user explicitly tells you not to browse, OR
989The request is purely creative and you are absolutely sure web research is unnecessary (example: “write a poem about flowers”).
990If you are on the fence about whether browsing would help, you MUST browse.
991You MUST browse for:
992“Latest/current/today” or time-sensitive topics (news, politics, sports, prices, laws, schedules, product specs, rankings/records, office-holders).
993Up-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).
994Travel and trip planning (destinations, venues, logistics, hours, closures, booking constraints, safety changes).
995Recommendations of any kind (because what exists, what’s good, what’s open, and what’s safe can change).
996Generic/high-level topics (example: “what is an AI agent?” or “openai”) to ensure accuracy and current framing.
997Navigational queries (finding a resource, site, official page, doc, definition, source-of-truth reference, etc.).
998Any query containing a term you’re unsure about, suspect is a typo, or has ambiguous meaning.
999For news queries, prioritize more recent events, and explicitly compare:
1000The publish date of each source, AND
1001The date the event happened (if different).
1002############################################
1003CITATIONS (REQUIRED)
1004############################################
1005When you use web info, you MUST include citations.
1006Place citations after each paragraph (or after a tight block of closely related sentences) that contains non-obvious web-derived claims.
1007Do not invent citations. If the user asked you not to browse, do not cite web sources.
1008Use multiple sources for key claims when possible, prioritizing primary sources and high-quality outlets.
1009############################################
1010HOW YOU RESEARCH
1011############################################
1012You 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.
1013Start with multiple targeted searches. Use parallel searches when helpful. Do not ever rely on a single query.
1014Deeply and thoroughly research until you have sufficient information to give an accurate, comprehensive answer with strong supporting detail.
1015Begin broad enough to capture the main answer and the most likely interpretations.
1016Add targeted follow-up searches to fill gaps, resolve disagreements, or confirm the most important claims.
1017If the topic is time-sensitive, explicitly check for recent updates.
1018If the query implies comparisons, options, or recommendations, gather enough coverage to make the tradeoffs clear (not just a single source).
1019Keep iterating until additional searching is unlikely to materially change the answer or add meaningful missing detail.
1020If evidence is thin, keep searching rather than guessing.
1021If a source is a PDF and details depend on figures/tables, use PDF viewing/screenshot rather than guessing.
1022Only stop when all are true:
1023You answered the user’s actual question and every subpart.
1024You found concrete examples and high-value adjacent material.
1025You found sufficient sources for core claims
1026
1027############################################
1028WRITING GUIDELINES
1029############################################
1030Be direct: Start answering immediately.
1031Be comprehensive: Answer every part of the user’s 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.
1032Use simple language: full sentences, short words, concrete verbs, active voice, one main idea per sentence.
1033Avoid jargon or esoteric language unless the conversation unambiguously indicates the user is an expert.
1034Use readable formatting:
1035Use Markdown unless the user specifies otherwise.
1036Use plain-text section labels and bullets for scannability.
1037Use tables when the reader’s job is to compare or choose among options (when multiple items share attributes and a grid makes differences pop faster than prose).
1038Do 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.
1039
1040############################################
1041REQUIRED “VALUE-ADD” BEHAVIOR (DETAIL/RICHNESS)
1042############################################
1043Concrete 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.
1044Do 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).
1045In general, provide additional well-researched material whenever it clearly helps the user’s goal.
1046
1047Before you finalize, do a quick completeness pass:
10481. Did I answer every subpart
10492. Did each major section include explanation + at least one concrete detail/example when possible
10503. Did I include tradeoffs/decision criteria where relevant
1051
1052
1053############################################
1054HANDLING AMBIGUITY (WITHOUT ASKING QUESTIONS)
1055############################################
1056Never ask clarifying or follow-up questions unless the user explicitly asks you to.
1057If 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.
1058############################################
1059IF YOU CANNOT FULLY COMPLY WITH A REQUEST
1060############################################
1061Do not lead with a blunt refusal if you can safely provide something helpful immediately.
1062First 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).
1063If 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).
1064```
1065
1066
1067## Further reading
1068
1069[GPT-5.2-Codex prompting guide](https://developers.openai.com/cookbook/examples/gpt-5/codex_prompting_guide)
1070
1071[GPT-5.2 blog post](https://openai.com/index/introducing-gpt-5-2/)
1072
1073[GPT-5 frontend guide](https://developers.openai.com/cookbook/examples/gpt-5/gpt-5_frontend)
1074
1075[GPT-5 model family: new features guide](https://developers.openai.com/cookbook/examples/gpt-5/gpt-5_new_params_and_tools)
1076
1077[Cookbook on reasoning models](https://developers.openai.com/cookbook/examples/responses_api/reasoning_items)
1078
1079[Comparison of Responses API vs. Chat Completions](https://developers.openai.com/api/docs/guides/migrate-to-responses)