GPT-6 Astra の使い方
GPT-6 Astra のベストプラクティス、機能、移行方法を紹介します。
はじめに
GPT-6 Astra は、OpenAI 史上最も高い知能を備えたモデルです。コンピューターの使用、ブラウジング、ソフトウェアエンジニアリング、科学、専門的な業務で最先端の性能を発揮します。コード、ブラウザ、専門業務用ソフトウェアを横断する複数ステップのワークフローを得意としています。複数の評価で、Astra は出力トークン数を大幅に抑えながら、より優れた結果を達成しています。そのため、トークン単価は高くても、タスクあたりの推定 API コストは従来のモデルを下回ります。
GPT-6 Astra は、アラインメントの面でも OpenAI 史上最も優れたモデルです。慎重に行動し、タスクの範囲を守り、透明性のあるコミュニケーションを行うことに優れています。指示に解釈の余地がある場合は、手元のコンテキストを使って通常の判断で補える部分を補い、回答によって結果が変わり得る場合には、要点を絞って質問します。新たな要件を取り入れ、求められれば方針を変更し、タスク全体を見失うことなく途中の質問にも答えます。
Astra を使って開発するには、Responses API リクエストで model を gpt-6-astra に設定します。
新着情報
- 非同期ツール呼び出し: アプリケーションがツールを実行している間も、GPT-6 Astra は推論を続けたり、ほかのツールを呼び出したり、リクエストのうち独立して対応できる部分に回答したりできます。関数またはカスタムツールに
async: trueを設定し、結果が用意できたら元のcall_idを使って返します。ツールの実行と未完了の作業の管理は、引き続きアプリケーションが行います。基本的な使い方と、開発者が定義する待機ツールのパターンについては、非同期ツール呼び出しを参照してください。 - ターン途中の指示変更: GPT-6 Astra が作業している間に、訂正や要件の変更など、ユーザーからの追加指示を送信できます。WebSocket 接続では、Responses API が完了済みの作業を保持し、更新内容を反映して処理を継続します。イベントの流れとツール結果の扱いについては、ターン途中の指示変更を参照してください。
- キャッシュを保持したまま会話途中で推論を変更:
configuration_update入力項目を追加すると、元のプロンプトプレフィックスを書き換えることなく、難しい作業では推論強度を上げ、定型的な追加対応では下げられます。変更後の推論強度は、別のconfiguration_update入力項目で上書きされるまで適用されます。例と互換性については、会話途中での推論の変更を参照してください。 - ミスアラインメントの監視: GPT-6 Astra の安全対策強化の一環として、OpenAI のシステムはミスアラインメントを非同期で監視し、必要に応じてアラートを発します。詳しくは、ミスアラインメントの監視を参照してください。
- 制限事項: GPT-6 Astra は推論強度の
noneをサポートしていません。EU データレジデンシーを利用する場合、GPT-6 Astra では Fast モードを利用できません。
GPT-6 Astra は、GPT-5.6 で利用できる既存の API 機能もサポートしています。これには、コンピューターの使用、構造化出力、ストリーミング、プログラムによるツール呼び出し、マルチエージェントオーケストレーション、プロンプトキャッシュ、推論の保持、コンパクション、Pro モードが含まれます。
プロンプトのベストプラクティス
GPT-6 Astra は、GPT-5.6 Sol などの従来のモデルよりも高い知能と能力を備えています。また、ユースケースに合わせたプロンプトによって最適化できる行動の傾向もあります。
GPT-6 Astra の行動特性
- 主体性とタスクの完遂:このモデルは、より効果的にユーザーと協働できるよう設計されているため、追加情報によって結果が大きく変わり得る場合には、ユーザーに質問する傾向が強くなっています。そのため、ユーザーが妥当な仮定を置いて作業を続けることを期待していても、作業を止めてしまう場合があります。
- 指示への追従:GPT-6 Astra は、従来のモデルよりも全般的に指示への追従能力が高く、動作をより細かく制御できます。一方で、スキルや
AGENTS.mdなどのファイルに含まれる指示の影響を、より強く受ける場合があります。モデルがアクセスできるスキルやその他のファイルを点検し、動作に影響する指示がないか確認することを 強く推奨します 。 - パーソナリティと文体:このモデルは、書式を整えた詳細な回答を返す傾向があり、複数のセッションで同じような表現を繰り返し使う場合があります。アプリケーションに必要な文体と構成を指定してください。
- サブエージェントへの委任:ワークフローで期待するほど頻繁には、作業を委任しない場合があります。並行作業でサブエージェントをいつ、どの程度使うべきか指定してください。
- テストと検証:コーディングタスクでは、完了と判断する前に念入りにテストする傾向があります。小さなタスクでは、そのタスクに必要な範囲を超えてテストを行う場合があります。
主体性とタスクの完遂
GPT-6 Astra は、GPT-5.6 Sol やそれ以前のモデルに比べ、長時間のタスクでも一貫性を保つことに概して優れています。また、従来のモデルなら仮定を置いて進めていた場面でも、確認を求める傾向が強くなっています。
より自律的な作業を促すには、まず次のプロンプトを使ってみてください。
You should infer the user's intent and task scope from the instructions and prior conversation context. Your job is to bias towards action and carry the user's intended task to completion.
When the user expresses intent to perform new work or fix an existing issue, persist until the user's intended goal is complete. Progress autonomously towards the user's goal (e.g. creating isolated worktrees / checkouts if needed, resolving merge conflicts, read-only actions, creating draft PRs etc.) unless they are clearly destructive or irreversible.
ユーザーの意図が不明確な場合、モデルは作業を進めるためにユーザーへ確認を求める傾向が強くなっています。ユーザーのプロンプトに許可の意図が含まれている場合は、作業を最後まで進めるよう指示してください。
When the user's prompt indicates a request for action, such as "can you...", "I want to...", "help me..." and similar expressions, treat these as instructions to do the work and take action. Do not stop at acknowledging capability (e.g. "Yes…"), proposing a plan, or offering to continue. Do not settle for a partial or "helpful enough" solution that does not fully satisfy the user's task to save time, effort or tokens. If a task requires sustained work, complete all the necessary work until the intended outcome is fulfilled.
具体的でレビュー可能な成果物を用意してから承認を求めるよう、モデルに指示してください。これにより、実行できる作業を終える前にタスクが止まるのを避けられ、多くの場合、完了までの時間も短くなります。
Before asking the user clarifying questions, you should complete the work that is already authorized from context and necessary to make the proposed action concrete and reviewable. The user should be approving a concrete, reviewable result. For example, before deploying a change, writing to an external application, merging a PR or publishing a site, do all the required work first so that user approval is the final step. You don't need user permission for reversible tasks, read-only actions, reviews or fixes, or anything for which authorization is provided earlier in the session or strongly implied from the task instruction.
Do not introduce unsolicited warnings, disclaimers, approval flows, or safety/compliance checklists due to hypothetical risk.
モデルはデフォルトで、作業を続けながら、回答を待たずに進められる質問をする傾向もあります。アプリケーションに必要な自律性の程度に合わせて、これらのプロンプトを調整してください。
指示への追従
GPT-6 Astra は長い指示にもより的確に従える一方で、コンテキスト内の情報の影響をより強く受ける場合があります。たとえば、スキルファイル内の不明確な指針や矛盾する指針によって、作業の早い段階でモデルが停止し、先に進めなくなることがあります。ユーザーの指示とスキルのどちらを優先するか、明示してください。
The user's instructions take precedence over guidelines provided in a skill. If explicit user instructions conflict with a skill's instructions, prioritize the user's instructions.
停止や方針変更の原因となったスキルと指示をモデルに示すよう求めることも、モデルの動作の透明性を高めるうえで効果的です。
If a skill causes you to ask for permission or confirmation, pause, leave requested work unfinished, or diverge from the user's intent, name and link to the exact SKILL.md file you read, quote the relevant instruction, and briefly explain how it applies. Distinguish explicit skill requirements from your interpretation of guidelines.
アプリケーションが多数のスキルや AGENTS.md などの指示ファイルを読み込む場合は、このプロンプトを使って、明示されずに作用している指針や矛盾する指針を見つけてください。
パーソナリティと文体
GPT-6 Astra は、回答の要点を拾いやすくするためにリスト、表、Markdown を使う傾向があります。アプリケーションで書式を控えた文章が必要な場合は、その希望を指定してください。
Default to using clear, concise paragraphs, each developing one main idea. Use lists only when the information is genuinely parallel, sequential, or easier to compare, and avoid nested lists unless the hierarchy cannot be expressed clearly in prose. Use plain, simple language: familiar words, concrete examples, and precise verbs. Prefer active voice and direct statements.
Make sure to state the main point clearly and early, then develop it with the explanation and detail the reader needs. Let each sentence build on what came before. Develop the points that matter and provide enough support to be useful.
技術的な内容を伝える際には、次のプロンプトが、明快で筋の通った表現と専門分野にふさわしい表現の両立に役立ちます。
Use plain language over jargon, and reference technical details only to the degree that it helps illustrate an idea or your work to the user. Communicate complex concepts in a clear and cohesive manner, and calibrate your writing to the level of background knowledge assumed from the user's prompt and context.
文章中の専門用語や決まり文句を減らすには、まず次のプロンプトを使ってみてください。
Avoid using slop words or phrases like "Bottom Line:" in conclusions, "delve," "foster," "leverage," "it's worth noting," "importantly," "Question? Answer." or "This isn't about X. It's about Y.", "genuinely" or hyphenated compound descriptions and adjectives. Do not use concluding summary statements such as "In short:..", "The simplest mental model is:...".
State the intended action directly. Avoid adding what you won't do, what will remain unchanged, or how you'll separate or categorize results. Do not use contrastive framing such as "X, not Y" or "X—not Y" that introduces an unprompted alternative that the user didn't ask about. Avoid invented compound labels like "exact-head checks" and "editorial-row layouts", vague qualifiers, and canned transitions; use plain verbs and prepositions to state the actual relationship directly.
サブエージェントへの委任
GPT-6 Astra は、作業を分割し、並行して動くサブエージェントに委任できるよう学習されています。ハーネスにマルチエージェントシステムを実装している場合は、次のプロンプトを使って、GPT-6 Astra が作業を委任する程度を調整してください。
If at any point you can parallelize work by delegating tasks to another agent (no matter if you are the root or subagent), you should do so using collaboration tools if it could save time or improve quality.
エージェント間のメッセージには、文法やスペースの誤りが含まれる場合があります。エージェント間のメッセージを読みやすくするには、次のプロンプトを使ってください。
Messages that you send to other agents and your final answer may be read by a human, so ensure they are legible. Always put proper spaces between words and/or numbers.
サブエージェントに作業を委任する方法やタイミングをプロンプトで指定すると、モデルはその指示によく従う傾向があります。ハーネスとマルチエージェントの実装に合わせて、この動作を調整してください。
テストと検証
コーディングタスクでは、変更に必要なテストと検証の程度を調整してください。これにより、小さな変更に対する不要なテストや繰り返しの確認を避けやすくなります。
Do not write tests for reversible, low-impact changes that mirror the implementation. If you do choose to verify your work with tests, make sure that the tests are meaningful and necessary to verify implementation.
Run tests appropriate to the change and complete required checks. Once those pass, broaden or repeat testing only when new changes, failures, or unresolved concerns justify it; otherwise, continue toward completing the task.
移行クイックスタート
Codex を使った移行
Codex は OpenAI ドキュメントスキルを使って、このガイドで推奨されている変更を適用できます。
$openai-docs migrate this project to GPT-6 Astra
他のコーディングエージェントでこのスキルを使用するには、Codex リポジトリからダウンロードしてください。
API とモデルのパラメータの更新
model を gpt-6-astra に設定し、次の点を確認してください。
- 推論強度: 現在
noneまたはminimalを使っている場合は、まずlowを試して結果を比較してください。それ以外の場合は、現在実際に適用されている推論強度を維持してください。Responses ではreasoning.effort、Chat Completions ではreasoning_effortを使います。 - ツール呼び出し: Responses API を使ってください。GPT-6 Astra は Chat Completions をサポートしていますが、ツール呼び出しには Responses が必要です。
- サポートされていないパラメータ:
temperature、top_p、top_logprobsを削除してください。Chat Completions では、logprobsも削除してください。Responses では、includeからmessage.output_text.logprobsを削除してください。 - Fast モード: EU データレジデンシーを利用する場合は、Standard 処理を使ってください。GPT-6 Astra は、EU データレジデンシーでの
service_tier: "fast"またはservice_tier: "priority"をサポートしていません。GPT-6 Astra の Fast モードには、レイテンシの SLA は含まれません。Fast モードの互換性を参照してください。 - 推論強度の変更: アプリケーションで応答ごとに推論強度を変更する場合は、通常の単一エージェントのリクエストで
configuration_update項目を使ってください。キャッシュ用のプロンプトプレフィックスを保持するため、リクエストレベルのreasoning.effortは変更しないでください。この機能を導入する前に、互換性に関する制限を確認してください。 - プロンプトキャッシュ: GPT-5.5 以前から移行する場合は、
prompt_cache_retentionをprompt_cache_options.ttlに置き換え、値を"30m"に設定してください。キャッシュの境界やキャッシュ書き込みの課金を含む、プロンプトキャッシュの変更点を確認してください。 - 不要な承認待ちによる停止: モデルが作業を進める前に何度も承認を求める問題が発生した場合は、主体性とタスクの完遂に関するガイダンスを使って、より自律的に実行するよう指示してください。指示への追従、文体、サブエージェントへの委任、テストについては、プロンプトのベストプラクティスのほかの項目を参照してください。
GPT-5.6 の使い方
GPT-5.6 と GPT-5.6 モデルファミリーのベストプラクティス、機能、移行方法を紹介します。
はじめに
GPT-5.6 は、複雑な本番ワークフローにおける品質と効率の新たな基準となるモデルです。特にトークン効率に優れており、レイアウト、視覚的な階層構造、デザイン上の判断など、フロントエンドの見栄えも向上しています。
GPT-5.6 では、モデルの命名方式も新しくなりました。gpt-5.6 エイリアスへのリクエストは、フラッグシップモデルの能力を備えた gpt-5.6-sol に送られます。低価格で高い性能が必要な場合は gpt-5.6-terra、大量の処理を効率よく実行する場合は gpt-5.6-luna を使用してください。
GPT-5.5 または GPT-5.4 から移行する場合は、現在の GPT-5.5 または GPT-5.4 の推論設定を出発点とし、代表的なタスクで同じ設定と 1 段階低い設定をテストしてください。GPT-5.6 は、多くの場合、より少ないトークンで品質を維持または向上できますが、最適な設定はワークロードによって異なります。
新着情報
- プログラムによるツール呼び出し: GPT-5.6 は JavaScript を記述し、ホストされたランタイムで対象ツールの呼び出し、呼び出し間での結果の受け渡し、中間出力の処理を実行できます。プログラムによるツール呼び出しは、範囲が明確でツールを多用し、各ステップの間にモデルによる新たな判断を必要としないワークフローに使用してください。プログラムによるツール呼び出しは ZDR に対応しており、コンテナの追加料金はかかりません。
- マルチエージェント [ベータ]: マルチエージェントでは、1 つの GPT-5.6 インスタンスが複数のサブエージェントを並列に連携させ、その結果を統合できます。Codex の Ultra モードと同様に、独立した作業に明確に分割できる複雑なタスクでは、実際の所要時間を短縮し、性能を向上できる可能性があります。マルチエージェントは Responses API のベータ機能として提供されており、開発者のフィードバックを基に改善を続けています。
- 明示的なプロンプトキャッシュ: GPT-5.6 では、再利用可能なプロンプトの接頭部分のうち、OpenAI がキャッシュする範囲を正確に指定できます。暗黙モードでの自動キャッシュも引き続き利用できます。OpenAI は、キャッシュへの書き込みにキャッシュされていない入力の 1.25 倍の料金を適用します。キャッシュの読み取りには、引き続き割引料金が適用されます。詳しくは、プロンプトキャッシュの設定方法をご覧ください。
- 推論の保持: GPT-5.6 は、利用可能な推論項目をターン間で再利用し、複数ターンにわたるやり取りの品質とキャッシュ効率を向上できます。動作は
reasoning.contextで選択します。詳しくは、呼び出し間で推論を保持する方法をご覧ください。 - 推論強度 Max: GPT-5.6 は、より多くの探索と検証が必要な難易度の高いタスク向けに、推論強度
maxをサポートしています。現在xhighを使用している場合は、代表的なワークロードで両方の設定を比較してください。 - Pro モード: GPT-5.6 は、モデルの処理量を増やすことで難しいタスクでの信頼性を高め、最終回答を 1 つ返すことができます。レイテンシやトークン使用量よりも品質を重視する場合は、
reasoning.mode: "pro"で有効にしてください。詳しくは、Pro モードの使い方をご覧ください。 - トークン効率: GPT-5.6 は、より少ない出力トークンでフラッグシップモデルに匹敵する性能を発揮します。
- フロントエンドデザイン: GPT-5.6 は、レイアウト、視覚的な階層構造、デザイン上の判断が向上しており、より洗練された使いやすいウェブサイトやアプリケーションを作成します。
- 意図の理解: GPT-5.6 は、ユーザーの根本的な目的や、どこまで作業してほしいかをコンテキストからより的確に推測できるため、多くの場合、すべての手順を指定する必要はありません。引き続き、対象分野の背景情報、必ず守るべき制約、承認が必要な範囲、成功基準を伝えてください。重要な曖昧さがある場合に、どのような条件で質問すべきかもモデルに伝えてください。
- 元の画像の詳細度: GPT-5.6 は、詳細度が
originalまたはautoの場合、画像の寸法を維持します。ただし、いずれかの辺が 65,535 ピクセルを超える画像は、その上限内に収まるように縮小されます。それでも30,000 パッチの上限を超える画像は、上限に合わせてさらにリサイズされるのではなく、API によって拒否されます。大きな画像は、入力トークン数やレイテンシを増加させる可能性があります。詳しくは、画像の詳細度の選び方をご覧ください。
安全対策
GPT-5.6 モデルでは、出力の生成中に、サイバー分野や生物学分野での悪用を検知する分類器がリアルタイムで実行されます。その結果、安全対策によって一部のリクエストがブロックまたは拒否される場合があります。また、分類器が出力を同期的にレビューする間、ストリーミングの途中で生成が数秒間停止し、リクエストの処理時間が長くなることもあります。安全対策は、正当な作業にも介入する場合があります。特に、防御目的と攻撃目的の活動が初期段階では似て見えるデュアルユース分野では、その可能性があります。
個々のエンドユーザーにサービスを提供するアプリケーションでは、ユーザーごとに一貫していてプライバシーを保護できる safety_identifier を、各リクエストに含めて送信してください。詳しくは、安全識別子の実装をご覧ください。
これらの安全対策は、悪意ある働きかけに対して堅牢かつ効果的に機能すると同時に、コードレビュー、脆弱性調査、パッチ開発、デバッグ、セキュリティ教育、防御目的のテストといった正当な作業へのアクセスを維持できるよう、継続的に改善しています。
移行クイックスタート
Codex による移行
Codex は、OpenAI Docs スキルを使って、このガイドで推奨する変更を適用できます。
$openai-docs migrate this project to the GPT-5.6 model family
このスキルを他のコーディングエージェントで使用するには、OpenAI のスキルリポジトリからダウンロードしてください。
API とモデルのパラメーターの更新
- ワークロードに合ったモデルを選択してください。フラッグシップモデルの能力が必要な場合は
gpt-5.6-sol、性能とコストのバランスを重視する場合はgpt-5.6-terra、大量の処理を効率よく実行する場合はgpt-5.6-lunaを使用します。gpt-5.6エイリアスへのリクエストはgpt-5.6-solに送られます。 - 推論、ツール呼び出し、複数ターンにわたるワークフローには、Responses API を使用してください。
reasoning.effortは、目的に合わせて設定してください。GPT-5.6 は、none、low、medium、high、xhigh、maxをサポートしています。- GPT-5.5 または GPT-5.4 から移行する場合は、現在の推論強度を基準として維持したうえで、1 段階低い設定と比較してください。
noneを使用している場合は、レイテンシの比較基準としてその設定を維持してください。推論やツールの使用がワークフローに役立つ場合は、lowもテストしてください。- バランスのよい出発点としては
mediumを、レイテンシを重視するワークロードにはlowを使用してください。 - 推論を増やすことで品質が向上すると測定で確認できた場合は、
highまたはxhighを使用してください。 maxは、品質を最優先する、特に難易度の高いワークロードに限定して使用してください。maxとxhighを比較し、ユースケースに最適な品質、レイテンシ、コストのバランスを見つけてください。
- Pro モードを使用するには、選択した GPT-5.6 モデルを維持したまま、Responses API で
reasoning.modeをproに設定してください。別の Pro モデルのスラッグに切り替える必要はありません。reasoning.effortは独立して選択します。省略した場合、GPT-5.6 は標準モードでも Pro モードでも、デフォルトでmediumを使用します。リクエストの例と課金の詳細については、推論モードをご覧ください。 - 過去の推論が現在のタスクにどの程度関連しているかに応じて、推論の保持を設定してください。GPT-5.6 モデルのデフォルトは
all_turns、それ以前のモデルのデフォルトはcurrent_turnです。- GPT-5.6 のデフォルトである
all_turnsを使用するには、reasoning.contextを省略するか、autoに設定してください。実際に適用されたモードは、レスポンスのreasoning.contextフィールドで確認できます。 - タスクの目的、前提、優先順位がターンをまたいで変わらない場合は、
reasoning.contextをall_turnsに設定してください。 all_turnsを使用する場合は、previous_response_idで会話を継続することで、過去のレスポンスの推論をモデルが利用できるようにしてください。- 履歴を手動で管理する場合は、過去のユーザー入力と、すべてのレスポンス出力項目を保持し、再送してください。
store: falseまたはゼロデータ保持を使用する場合は、API がデフォルトで返す暗号化された推論項目を再送してください。 - 過去の推論が現在のタスクに関連しなくなった場合は、
reasoning.contextをcurrent_turnに設定してください。
- GPT-5.6 のデフォルトである
- プロンプトキャッシュを見直してください。暗黙的なキャッシュを引き続き使用するために、コードを変更する必要はありません。GPT-5.6 のキャッシュへの書き込み料金は、キャッシュされていない入力の 1.25 倍なので、
cached_tokensとcache_write_tokensを追跡して、差し引きのコストを把握してください。不要な書き込みを避けるには、明示的なブレークポイントまたはprompt_cache_options.mode: "explicit"を使用し、prompt_cache_retentionをprompt_cache_options.ttlに置き換えてください。 - プログラムによるツール呼び出しを使用するには、
programmatic_tool_callingツールを追加し、allowed_callersで対象ツールの利用を許可してください。各呼び出しのcall_idとcallerの関連付けを維持しながら、program項目、プログラムが発行する関数呼び出し、program_output項目を処理できるようにアプリケーションを更新してください。リクエストと処理の継続の例については、プログラムによるツール呼び出しガイドをご覧ください。- 代表的なタスクで、PTC を有効にしたワークフローのベンチマークを実施してください。タスクの成功、最終回答の完全性、必要な根拠、総トークン数、レイテンシ、コストを比較します。呼び出し、ターン、中間出力の数が減っても、最終回答が必要な品質基準を満たしていなければ改善とは言えません。
プロンプトのベストプラクティス
無駄の少ないプロンプト
重複する指示や例を削除し、ツールの説明を簡素化することで、タスクの性能とトークン効率が向上する可能性があります。社内のコーディングエージェント評価の実行結果から抽出したサンプルでは、システムプロンプトを簡潔にした構成で、評価スコアが約 10–15% 向上し、総トークン数が 41–66%、コストが 33–67% 削減されました。結果はワークロードによって異なるため、これらの数値は傾向を示す目安と捉え、実際のアプリケーションの代表的なタスクで変更の効果を検証してください。
重要な指針を失わずにプロンプトを簡素化するには、次の点を意識してください。
- すでに機能しているプロンプトとツールの構成を出発点にしてください。指示、例、ツールを一度に 1 グループずつ削除し、そのたびに同じ評価を再実行してください。
- 各指示は 1 回だけ記述してください。
- タスクに関連するツールだけをモデルに提供し、説明は簡潔かつ正確にしてください。
- プロダクトの要件を表している例や文体の指針、または測定で確認された不足を補う例や指針は残してください。
- 実行開始時だけでなく、会話が長くなる過程でもコンテキストを追跡してください。長いセッションでは、プロンプトやツールの内容の重複による影響が大きくなることがあります。
自律的に進める範囲と承認が必要な範囲の定義
GPT-5.6 は、複数のステップからなるタスクを自発的に、粘り強く実行できます。各リクエストがどこまでの行動を許可するかを定義してください。これにより、モデルは安全で範囲内の作業を不要な中断なく継続しつつ、外部への操作、破壊的な操作、費用のかかる操作、作業範囲を広げる操作の前には停止できます。
通常は、次のような簡潔なポリシーで十分です。
For requests to answer, explain, review, diagnose, or plan, inspect the relevant
materials and report the result. Do not implement changes unless the request also
asks for them.
For requests to change, build, or fix, make the requested in-scope local changes
and run relevant non-destructive validation without asking first.
Require confirmation for external writes, destructive actions, purchases, or a
material expansion of scope.
ファイルの読み取り、ログの確認、対象範囲内のコード編集、テストの実行など、安全なローカル操作を明示してください。ポリシーは 1 か所にまとめ、各ルールは 1 回だけ記述します。「まず確認する」「変更しない」「承認を待つ」といった指示を繰り返すと、安全で想定どおりの操作に対しても、不要な承認リクエストが発生することがあります。
回答の長さと文体の設定
GPT-5.6 は、デフォルトで GPT-5.5 よりも簡潔に回答する傾向があります。移行時には、「簡潔に」「短くまとめて」といった、短さを求める一般的な指示が引き続き有効かを確認してください。タスクによっては不要であり、回答が短くなりすぎる場合もあります。アプリケーションに必要な出力を安定して得られる場合は、こうした指示を残してください。
リクエスト間でより一貫した制御を行うには、text.verbosity でデフォルトの詳しさを設定し、タスク固有の要件をプロンプトで指定してください。
text.verbosity によるデフォルトの設定
リクエストのデフォルトの詳しさとして、low、medium、high のいずれかを選択してください。タスク固有の長さ、構成、必須の内容はプロンプトで指定します。API の例については、text.verbosity の設定をご覧ください。
短い回答に必須の内容の指定
短い回答が求められるタスクでは、モデルが残すべき情報と省略できる詳細を明示します。たとえば、次のように指定します。
Lead with the conclusion. Include the evidence needed to support it, any material
caveat, and the next action. Omit secondary detail and repetition.
Keep all required facts, decisions, caveats, and next steps. Trim introductions,
repetition, generic reassurance, and optional background first.
これにより、タスクの完了に必要な内容を残し、そのうえで重要度の低い詳細を削るという優先順位がモデルに明確に伝わります。
文体の指定
「フレンドリー」「共感的」といった大まかな表現では、解釈が曖昧になりがちです。答えをどの程度ストレートに伝えるか、どのような場合に問題への理解を示すか、安心させる言葉や結びの挨拶を添えるべきかなど、プロダクトの文体を決める具体的な書き方を説明します。
State the answer directly. If the user reports a problem, acknowledge the
specific issue before giving the next step. Use reassurance only when it is
relevant. Omit generic praise and unnecessary sign-offs.
Pro モード
品質を最優先する場合の Pro モード
Pro モードは、リクエストに対してモデルがより多くの処理を行ってから、最終回答を 1 つ返す Responses API の実行モードです。難しいタスクで信頼性を高められる一方、レイテンシが増加し、その処理で使われたトークンは合算して使用量に計上されます。これらのトークンには、選択したモデルの標準トークン料金が適用されます。
複雑な最適化、価値の高いコーディングやレビュー、明確な評価基準に基づく深い分析など、わずかな品質向上が結果に大きく影響し、その恩恵を受けるだけの難しさがあるタスクには Pro モードを使います。日常的な作業、低レイテンシが求められる処理、大量の処理には標準モードを優先します。また、評価で Pro モードによる有意な改善が見られない場合も、標準モードを優先します。
推論モードと推論強度は独立した設定です。Pro モードは、どの GPT-5.6 モデルでも、そのモデルがサポートする推論強度と組み合わせて使えます。まず標準モードの基準となる構成と同じモデル、同じ推論強度を使い、代表的なタスクで構成を比較します。推論強度を最も高くすれば常に最適なバランスになるとは限りません。
API での Pro モードの設定
API リクエストで Pro モードを有効にします。プロンプトは、標準モードで使っている成果重視のものをそのまま使います。目標、関連するコンテキスト、制約、必要な根拠、成功基準、出力形式を明示してください。モデルに「Pro モードを使って」「もっと深く考えて」と指示したり、回答の候補を複数生成するよう求めたりする必要はありません。
例を示します。
Review this database migration plan for failure modes that could cause data loss
or extended downtime. For each finding, cite the relevant step, estimate impact
and likelihood, and recommend a specific mitigation. Return the five most
important risks in severity order.
品質とコストの比較
同じ代表的なタスクで標準モードと Pro モードを比較します。タスクの成功、回答の完全性、必要な根拠、総トークン数、レイテンシ、コストを評価します。モデルの追加処理に見合う品質や信頼性の向上が得られる場面に絞って Pro モードを使います。
詳しくは、推論モードガイドをご覧ください。
プログラムによるツール呼び出し
タスクの特性に応じたプログラムによるツール呼び出しの選択
プログラムによるツール呼び出し(PTC)は、複数のツールの結果や大量の中間出力をコードで処理し、大幅に小さい構造化された結果を返せる、範囲の明確なワークフローに最適です。フィルタリング、結合、ランキング、重複排除、集計、検証など、処理内容を予測できる作業に使います。
呼び出しが複数ある、並列で実行する、依存関係があるというだけでは、プログラムによるツール呼び出しを使う理由としては不十分です。次の場合は、PTC を使わずにツールを直接呼び出す方法を優先します。
- 1 回の呼び出しで十分な場合
- 中間出力がすでに小さい場合
- 個々の結果によってモデルの次の判断が変わりうる場合
- 操作に承認が必要な場合
- 最終出力に引用やネイティブ形式の成果物を保持する必要がある場合
タスクに応じた呼び出し方法の指定
適切な呼び出し方法を選ばせるために、ツールが利用可能かどうかや「プログラムによるツール呼び出しを効率的に使って」といった一般的な指示だけに頼らないでください。直接呼び出しとプログラムによる呼び出しの両方が利用できる場合は、次の点を明示します。
- プログラムによるツール呼び出しを使う工程とその範囲
- 呼び出しを許可するツール
- 厳密な出力スキーマと必要な根拠
- 同時実行数と再試行回数の上限、および停止条件
- 直接呼び出しで行う作業
ツールの説明には、想定される戻り値のフィールドと型、エラー時の動作を記載します。モデルがプログラムを書く前に戻り値の構造を判断できない場合は、ツールの直接呼び出しを優先します。そうすれば、結果を確認してから、その使い方を判断できます。
両方の呼び出し方法が必要な場合は、処理を引き継ぐ箇所を 1 つ明確に定め、それ以外で呼び出し方法を切り替えたり、完了した作業を繰り返したりしないようモデルに指示します。
例を示します。
<tool_orchestration>
Use Programmatic Tool Calling for [bounded stage] using only [eligible tools].
Run independent calls concurrently when safe. Use only documented tool input
and output fields.
Process and reduce the intermediate results, then emit exactly [output schema],
including the evidence needed for the final answer.
Stop when [condition] is met. Retry transient failures at most [R] times.
Do not repeat completed calls or perform side-effecting actions. If a required
result is still missing, return a clear structured failure.
Use direct tool calls for [semantic judgment, approval, or final validation].
</tool_orchestration>
最終回答の評価
program_output 項目とアシスタントの最終的な message は別々の出力なので、必ず両方をテストします。プログラムが正しいレコードを返していても、メッセージには必須のフィールド、引用、注意事項が含まれていない可能性があります。
同じ代表的なタスクで、直接呼び出しとプログラムによる呼び出しを比較します。最終応答が正しく、必要な内容を網羅し、求められる根拠を含んでいるかを確認します。そのうえで、総トークン数、レイテンシ、コスト、呼び出し回数、ターン数、再試行回数を比較します。リソース使用量の削減を改善とみなすのは、削減後も応答が既存の評価に合格する場合だけにします。
詳しくは、プログラムによるツール呼び出しガイドをご覧ください。
GPT-5.5 の使い方
GPT-5.5 のベストプラクティス、機能、移行ガイドを紹介します。
はじめに
GPT-5.5 は、本番環境の複雑なワークフローで求められる性能の水準を引き上げます。コーディングのユースケース、ツールを多用するエージェント、根拠に基づいて応答するアシスタント、長いコンテキストからの情報取得、製品仕様から計画を作成するワークフロー、そして実行品質と応答の完成度が重要な顧客向けワークフローに適しています。
GPT-5.5 を最大限に活用するには、gpt-5.2 や gpt-5.4 をそのまま置き換えるモデルではなく、新たに調整が必要なモデルファミリーとして扱ってください。移行時は、従来のプロンプト群に含まれる指示をすべて引き継ぐのではなく、新しいベースラインから始めます。まず、製品として満たすべき要件を維持できる最小限のプロンプトを用意し、代表的な例で検証しながら、推論強度、詳細度、ツールの説明、出力形式を調整してください。
GPT-5.5 は、プロンプトキャッシュ、ホスト型ツール、ツール検索、コンパクション、手動で再送信するアシスタント項目の phase の処理など、GPT-5.4 ですでに利用できたすべての API 機能をサポートしています。
効果的なプロンプトのパターン例については、プロンプトのベストプラクティスを参照してください。
新着情報
- 推論の効率向上: GPT-5.5 は、同じ推論強度でも、従来のモデルより少ない推論トークンで優れた結果を得られます。特に、複雑なワークフロー、ツールを多用するワークフロー、複数のステップを伴うワークフローでは、トークンの削減効果が積み重なるため有用です。
- 成果を重視したプロンプトによるタスク実行能力の向上: GPT-5.5 は、明確な目標に基づいて作業し、制約を守りながら、製品の意図を具体的な次のステップに落とし込む能力が向上しています。期待する成果、成功基準、許容する副作用、根拠に関するルール、出力の構成を記述してください。手順そのものが重要な場合を除き、作業をステップごとに指示することは避けてください。
- ツール使用の能力と精度の向上: GPT-5.5 は、利用可能なツールが多い環境、複数のステップからなるサービスのワークフロー、長時間にわたるエージェントのタスクで特に有用です。ツールの選択や引数の使い方が、より正確になる傾向があります。
- より洗練された語り口と、より率直な表現: GPT-5.5 は、プロンプトで細かく補助しなくても、温かみがあり読みやすい回答を生成することが多くなっています。
動作の変更点
-
推論強度のデフォルトを
mediumに変更: GPT-5.5 の推論強度は、デフォルトでmediumです。品質、信頼性、レイテンシ、コストのバランスが取れた推奨の初期設定として、mediumを使用してください。レイテンシが重要なワークフローでも、ツールの使用、計画、検索、複数ステップの意思決定が必要な場合は、noneより先にlowを評価してください。noneは、軽量な音声のやり取り、高速な情報取得、分類など、推論や連鎖的なツール呼び出しを必要とせず、レイテンシが最優先されるタスクに限って使用してください。highやxhighに引き上げるのは、レイテンシとコストの増加に見合う、測定可能な品質向上が評価で確認できた場合だけにしてください。推奨設定の詳細は、リーズニングモデルのドキュメントを参照してください。推論強度は、高ければよいとは限りません。タスクに矛盾する指示がある場合、停止基準が曖昧な場合、ツールへのアクセスに明確な制限がない場合は、推論強度を上げると、考えすぎや不要な検索、出力品質の低下につながることがあります。推論強度を上げるのは、測定可能な品質向上が評価で確認できた場合だけにしてください。
-
画像入力で保持する視覚的な詳細情報をデフォルトで増加: GPT-5.5 では、より多くの視覚的な詳細情報を保持し、コンピューターの使用の性能を向上させるため、画像入力のデフォルトの処理を変更しています。
image_detailが未設定、またはautoに設定されている場合、モデルはoriginalの動作を使用するようになり、総画素数 10,240,000 ピクセル、または一辺 6,000 ピクセルの上限に達するまで、画像をリサイズせずに保持します。highを使う場合は、その値を直接指定してください。この設定では、総画素数 2,500,000 ピクセル、または一辺 2,048 ピクセルの上限に達するまで、画像をリサイズせずに保持します。lowはコンテキストの効率的な利用を重視するようになり、一辺が 512 ピクセルの上限を超える画像を、従来のモデルより積極的に縮小します。画像と視覚認識のドキュメントを参照してください。 -
指示への追従性の向上: GPT-5.5 はプロンプトを文字どおり、かつ漏れなく解釈するため、製品上必要な場合に、具体的で詳しい指示を与えられます。特に、長時間にわたるワークフロー、ツールを多用するワークフロー、根拠を収集するワークフローでは、成功基準と停止ルールを定義してください。成果を重視したプロンプトの作成と適切な具体性の維持を参照してください。
-
より簡潔で率直なデフォルトのスタイル: GPT-5.5 は、デフォルトで無駄が少なく、率直で、タスクに集中した応答をする傾向があります。これは本番環境の多くのワークフローで有用ですが、顧客向けの体験や対話型の体験では、パーソナリティ、温かみ、理由の説明、書式について明示的な指示が必要になることがあります。
text.verbosityは意図を持って設定してください。デフォルトはmediumですが、簡潔な応答が必要なら、多くの場合はlowから始める方が適しています。プロンプトのベストプラクティスを参照してください。 -
コーディングのワークフローに必要なオーケストレーションの強化: GPT-5.5 は、計画、ツールの使用、コードベースの探索、検証、複数ステップの実行を必要とする複雑なコーディングタスクに、より適しています。コーディングエージェントには、再利用、サブエージェントへの委任、テストの要件、受け入れ基準、作業を続ける条件と支援を求める条件を明示してください。
移行クイックスタート
Codex による移行の自動化
Codex は、OpenAI Docs スキルを使って、このガイドで推奨する変更を適用できます。
$openai-docs migrate this project to gpt-5.5
このスキルを他のコーディングエージェントで使うには、OpenAI のスキルリポジトリからダウンロードしてください。
API とモデルのパラメーター
- モデルのスラッグを
gpt-5.5に更新してください。 - 推論、ツール呼び出し、複数ターンのやり取りを伴うユースケースでは、Responses API を使用してください。
reasoning.effortを調整してください。効率的な推論にはlow、レイテンシと性能のバランスを取るにはmedium、高度な推論が必要でレイテンシの重要度が低い複雑なエージェント型タスクにはhigh、最も難しい非同期のエージェント型タスクやモデルの知的能力の限界を測る評価にはxhighを使用してください。リーズニングモデルのドキュメントを参照してください。- より簡潔な応答になるよう設定するには、
text.verbosityをlowに設定してください。GPT-5.5 では、GPT-5.4 で詳細度をlowに設定した場合よりも、応答が相対的にさらに簡潔になります。 - ツールを多用するワークフローや長時間にわたるワークフローでは、アプリケーションが
phase、前置き、アシスタント項目の再送信を正しく処理していることを確認してください。 - 精度、トークン消費量、エンドツーエンドのレイテンシについて、他のモデルとベンチマークで比較してください。
プロンプト
- 期待する成果と成功基準を明示してください。
- ステップごとの詳細な手順の指示を減らすか、削除してください。製品上その手順が必要な場合を除き、進め方は GPT-5.5 に任せてください。
- 可能な限り、プロンプトから出力スキーマの定義を削除してください。代わりに構造化出力を使用してください。
- 静的な部分を先頭に、動的な部分を末尾に配置して、プロンプトをキャッシュに適した形にしてください。
- 現在の日付は削除してください。モデルはすでに UTC での現在の日付を認識しています。
- プロンプトのベストプラクティスを参考に、プロンプトを見直して最適化してください。
リーズニングモデルの使い方
このガイドは GPT-5 シリーズのモデルに適用されます。ワークロードをリーズニングモデルに移行する際は、その都度確認することをおすすめします。GPT-5.5 は、以前のモデルで初めて導入された多くの機能を引き継いでいます。以前の GPT-5 モデル、GPT-4.1、o3 などのリーズニングモデルから移行する場合も、これらの機能を改めて確認してください。
これらの機能の一部は、プロンプト自体ではなく API の設定やオーケストレーションで扱うため、見落とされがちです。Responses API、推論の制御、詳細度、構造化出力、プロンプトキャッシュ、ツール設計、ホスト型ツール、状態管理を組み合わせることで、リーズニングモデルの知的能力、信頼性、レイテンシ、コストを最適化できます。
- Responses API: GPT-5.5 は、Responses API で最もよく性能を発揮します。複数ターンにわたる状態の管理には
previous_response_idを使用してください。ステートレスなフローやゼロデータ保持のフローでは、返された出力項目のうち関連するものを、毎ターン送り返してください。詳細は、前の応答からのコンテキストの受け渡しを参照してください。 - 推論強度:
reasoning.effortを使って、low、medium、high、xhighから選択してください。デフォルトはmediumですが、多くのワークロードではlowでも良好な結果が得られます。noneは、知的能力より低レイテンシを重視するユースケースに限って使用してください。詳しい推奨事項は、リーズニングモデルを参照してください。 - 詳細度:
text.verbosityを使って出力の長さを制御してください。最終回答の長さと推論の品質は別々に扱い、必要に応じて、語数の上限、セクション数、表の幅、JSON のみで出力することなどを指定してください。 - 構造化出力: 期待する出力スキーマをプロンプト内で説明することは避けてください。自動検証と精度向上のために、構造化出力を使用してください。
- プロンプトキャッシュ: プロンプトキャッシュは、条件を満たす長いプロンプトに自動的に適用され、レイテンシと入力トークンのコストを削減できます。キャッシュヒットを最大化するには、変わらない内容をリクエストの先頭に配置してください。ユーザーごとに変わるコンテキストは末尾近くに配置してください。
usage.prompt_tokens_details.cached_tokensを追跡して再利用の状況を測定してください。再利用可能なプレフィックスを共有するリクエストでは、prompt_cache_keyの値を一定にしてください。このキーは、関連するリクエストを同じキャッシュに振り分けるのに役立ち、GPT-5.5 のキャッシュヒット率を最適化するうえで重要です。リクエストが多いグループでは、より多くのキーにトラフィックを分散するためのガイダンスに従ってください。 - ツール呼び出し: GPT-5.5 は、関数ツールやツールを多用するエージェントのワークフローなど、GPT-5.4 と同じツール呼び出しのパターンをサポートしています。ツール固有の指示は、できるだけそのツール自体の説明に記載してください。ツールの機能、使用する場面、必要な入力、副作用、再試行の安全性、よくあるエラーの種類などが該当します。ツール固有のコンテキストをシステム指示に追加するのは、複数のツールに共通して適用される場合、またはエージェントの動作方針を大きく変える場合だけにしてください。
- ホスト型ツールとツール検索: ウェブ検索、ファイル検索、Code Interpreter、画像生成、コンピューターの使用など、ワークフローに適したOpenAI ホスト型ツールがある場合は、優先して使用してください。ホスト型ツールを使うと、独自のオーケストレーションを実装する負担を軽減し、一般的なツール利用のパターンを Responses API や Agents SDK と整合させられます。独自のシステムを呼び出す場合、ドメイン固有の副作用を確実に適用する場合、内部の業務ワークフローを利用できるようにする場合は、カスタム関数ツールを使用してください。ツールカタログが大規模な場合は、ツール検索を使ってツール定義の読み込みを遅らせ、関連するものだけを読み込むことを検討してください。
- ツール使用前の前置き: 前置きを使うと、モデルが最終応答を生成する前に、ユーザーが役立つ最初の状況報告を確認できるため、チャットの UX を改善できます。また、ツール使用の流れも理解しやすくなります。モデルは、これから何を確認または実行するかを伝え、ツールの結果を受け取った後は、同じアシスタントの状態から作業を続けられます。
phaseの処理: アプリケーションがprevious_response_idを使わず、毎ターン出力項目を送り返して Responses の状態を手動で管理する場合は、返されたアシスタントの出力項目にあるphaseパラメーターを保持し、変更せずに送り返してください。これは、推論強度、前置き、繰り返しのツール呼び出しを使用する場合に特に重要です。Phase パラメーターを参照してください。- コンパクション: 長時間実行するエージェントでは、会話や状態のコンパクションを計画的に使用してください。完了したアクション、現在有効な前提、ID、ツールの実行結果、未解決の阻害要因、次の具体的な目標を保持してください。
- Agents SDK: 新しいエージェント型システムでは、オーケストレーションを一から構築し直すのではなく、ツールのオーケストレーション、トレーシング、ハンドオフ、状態管理に、最新の Agents SDK のパターンを使用してください。
- 現在の日付: GPT-5.5 は UTC での現在の日付を認識しています。システム指示に現在の日付を追加する必要はありません。日付やタイムゾーンのコンテキストを明示的に追加するのは、業務固有のタイムゾーン、ポリシーの発効日、ユーザーの現地の日付など、UTC 以外の基準をアプリケーションが必要とする場合だけにしてください。
プロンプトのベストプラクティス
GPT-5.5 は、プロンプトで成果を定義し、効率的な解決方法をモデル自身が選べる余地を残したときに、最もよく性能を発揮します。従来のモデルと比べて、多くの場合は、より短く成果を重視したプロンプトを使えます。望ましい結果、重要な制約、利用できる根拠、最終回答に含める内容を記述してください。
従来のプロンプト群に含まれる指示を、すべて引き継ぐことは避けてください。以前のモデルは、意図した方向に作業を進めるために多くの補助を必要としていたため、従来のプロンプトは手順を過剰に指定していることがよくあります。GPT-5.5 では、そうした指示がノイズを増やし、モデルの探索範囲を狭めたり、回答を過度に機械的にしたりすることがあります。
ここで紹介するパターンは出発点です。製品のインターフェース、ツール、評価、目指すユーザー体験に合わせて調整してください。
パーソナリティと動作
GPT-5.5 のデフォルトのスタイルは、無駄が少なく、率直で、タスクに集中しています。応答の焦点がぶれず、動作を制御しやすく、会話の不要な水増しを避けられるため、本番環境のシステムに有用です。
顧客向けアシスタント、サポートのワークフロー、コーチング体験などの対話型製品では、パーソナリティと協働スタイルの両方を定義してください。
- パーソナリティ は、語調、温かみ、率直さ、フォーマルさ、ユーモア、共感、表現の洗練度など、アシスタントの話し方を決めます。
- 協働スタイル は、質問をするタイミング、仮定を置くタイミング、自発的に行動する度合い、背景情報を伝える量、作業を確認するタイミング、不確実性やリスクへの対処方法など、アシスタントの作業の進め方を決めます。
どちらも短くまとめてください。パーソナリティの指示はユーザー体験を形作り、協働の指示はタスクの進め方を形作るものです。いずれも、明確な目標、成功基準、ツールのルール、停止条件の代わりにはなりません。
落ち着いてタスクに集中するアシスタント向けのパーソナリティ指示ブロックの例:
# Personality
You are a capable collaborator: approachable, steady, and direct. Assume the user is competent and acting in good faith, and respond with patience, respect, and practical helpfulness.
Prefer making progress over stopping for clarification when the request is already clear enough to attempt. Use context and reasonable assumptions to move forward. Ask for clarification only when the missing information would materially change the answer or create meaningful risk, and keep any question narrow.
Stay concise without becoming curt. Give enough context for the user to understand and trust the answer, then stop. Use examples, comparisons, or simple analogies when they make the point easier to grasp. When correcting the user or disagreeing, be candid but constructive. When an error is pointed out, acknowledge it plainly and focus on fixing it.
Match the user's tone within professional bounds. Avoid emojis and profanity by default, unless the user explicitly asks for that style or has clearly established it as appropriate for the conversation.
表現豊かで協調的なアシスタント向けのパーソナリティ設定例:
# Personality
Adopt a vivid conversational presence: intelligent, curious, playful when appropriate, and attentive to the user's thinking. Ask good questions when the problem is blurry, then become decisive once there is enough context.
Be warm, collaborative, and polished. Conversation should feel easy and alive, but not chatty for its own sake. Offer a real point of view rather than merely mirroring the user, while staying responsive to their goals and constraints.
Be thoughtful and grounded when the task calls for synthesis or advice. State a clear recommendation when you have enough context, explain important tradeoffs, and name uncertainty without becoming evasive.
より表現豊かなプロダクトにするには、温かさ、好奇心、ユーモア、独自の視点などを明示的に指定します。ただし、設定は短くまとめてください。パーソナリティはユーザー体験を形作るために使い、曖昧な目標や不足しているタスクの指示を補う手段にはしないでください。
前置きによる最初のトークン表示までの時間短縮
ストリーミングを使うアプリケーションでは、ユーザーは最初の応答が表示されるまでの待ち時間を意識します。GPT-5.5 は、テキストを表示する前に、推論、計画、ツール呼び出しの準備に時間をかけることがあります。
時間がかかるタスクやツールを多用するタスクでは、短い前置きから始めるようモデルに指示します。リクエストを受け付けたことと最初の手順を、ユーザーに見える短いメッセージで伝えるものです。これにより、タスク自体を変えずに、体感的な応答速度を改善できます。
複数の手順が必要になる可能性があるタスク、ツール呼び出しが必要なタスク、長時間実行するエージェントのワークフローでは、このパターンを使ってください。
Before any tool calls for a multi-step task, send a short user-visible update that acknowledges the request and states the first step. Keep it to one or two sentences.
メッセージのフェーズを区別して扱えるコーディングエージェントでは、より明確に指示できます:
You must always start with an intermediary update before any content in the analysis channel if the task will require calling tools. The user update should acknowledge the request and explain your first step.
成果を起点とするプロンプトと停止条件
GPT-5.5 は、目指す成果、成功基準、制約、利用可能なコンテキストをプロンプトで定義し、達成方法の選択をモデルに任せると、最も力を発揮します。
多くのタスクでは、手順を一つひとつ指定するより、到達すべき目標を説明してください。そうすることで、モデルはタスクに合った検索方法、ツール、推論戦略を選べます。
推奨する例:
Resolve the customer's issue end to end.
Success means:
- the eligibility decision is made from the available policy and account data
- any allowed action is completed before responding
- the final answer includes completed_actions, customer_message, and blockers
- if evidence is missing, ask for the smallest missing field
不要な絶対ルールは避けてください。 従来のプロンプトでは、モデルの動作を制御するために、ALWAYS、NEVER、must、only のような厳格な指示がよく使われています。こうした表現は、安全ルール、必須の出力フィールド、決して実行してはならない行為など、例外なく守るべき事項に使ってください。検索するタイミング、確認を求めるタイミング、ツールを使うかどうか、反復を続けるかどうかといった状況に応じた判断には、判断基準を示すルールを使ってください。
すべての手順が本当に必要な場合を除き、次のような指示は避けてください:
First inspect A, then inspect B, then compare every field, then think through
all possible exceptions, then decide which tool to call, then call the tool,
then explain the entire process to the user.
明確な停止条件を追加します:
Resolve the user query in the fewest useful tool loops, but do not let loop minimization outrank correctness, accessible fallback evidence, calculations, or required citation tags for factual claims.
After each result, ask: "Can I answer the user's core request now with useful evidence and citations for the factual claims?" If yes, answer.
根拠が不足している場合の動作を定義します:
Use the minimum evidence sufficient to answer correctly, cite it precisely, then stop.
書式設定
GPT-5.5 は、出力の形式や構造を柔軟に指定できます。わかりやすさの向上やプロダクトへの適合に役立つ場合に活用してください。
text.verbosity を設定し、期待する出力形式を説明してください。複雑な構造は、理解しやすくなる場合や、プロダクトの UI が安定した形式の成果物を必要とする場合に限って使います。API での text.verbosity のデフォルト値は medium です。より短く簡潔な応答が望ましい場合は、low を使ってください。
シンプルな会話形式:
Let formatting serve comprehension. Use plain paragraphs as the default format for normal conversation, explanations, reports, documentation, and technical writeups. Keep the presentation clean and readable without making the structure feel heavier than the content.
Use headers, bold text, bullets, and numbered lists sparingly. Reach for them when the user requests them, when the answer needs clear comparison or ranking, or when the information would be harder to scan as prose. Otherwise, favor short paragraphs and natural transitions.
Respect formatting preferences from the user. If they ask for a terse answer, minimal formatting, no bullets, no headers, or a specific structure, follow that preference unless there is a strong reason not to.
想定読者と長さを明確に指定します:
Write for a senior business audience. Keep the answer under 400 words. Use short paragraphs and only include bullets when they improve scannability. Prioritize the conclusion first, then the reasoning, then caveats.
編集、書き換え、要約、顧客向けメッセージの作成では、文体の改善を求める前に、何を維持すべきかをモデルに伝えてください。文章を長くせずに表現を整えたい場合に有効なパターンです。
Preserve the requested artifact, length, structure, and genre first. Quietly improve clarity, flow, and correctness. Do not add new claims, extra sections, or a more promotional tone unless explicitly requested.
グラウンディング、引用、情報取得の上限
根拠に基づいた回答を得るには、引用のルールをプロンプトに含めてください。どの内容に裏付けが必要か、どの程度の根拠があれば十分か、根拠が不足している場合にモデルがどう対応すべきかを定義します。根拠がないことを、そのまま否定の事実として扱ってはいけません。詳しい説明と例は、引用の書式設定ガイドを参照してください。
情報取得の上限の明示
情報取得の上限は、検索を終了するためのルールです。どの時点で根拠が十分にそろったと判断すべきかをモデルに伝えます。
For ordinary Q&A, start with one broad search using short, discriminative keywords. If the top results contain enough citable support for the core request, answer from those results instead of searching again.
Make another retrieval call only when:
- The top results do not answer the core question.
- A required fact, parameter, owner, date, ID, or source is missing.
- The user asked for exhaustive coverage, a comparison, or a comprehensive list.
- A specific document, URL, email, meeting, record, or code artifact must be read.
- The answer would otherwise contain an important unsupported factual claim.
Do not search again to improve phrasing, add examples, cite nonessential details, or support wording that can safely be made more generic.
創造的な文章作成のためのガードレール
文章を作成するタスクでは、どの主張を情報源に基づかせる必要があり、どの部分は創造的に書いてよいかをモデルに伝えてください。これは、スライド、ローンチ時の宣伝文、顧客向けの要約、説明用のトーク原稿、経営層向けの短い説明文、ストーリーの構成を作る際に特に重要です。
For creative or generative requests such as slides, leadership blurbs, outbound copy, summaries for sharing, talk tracks, or narrative framing, distinguish source-backed facts from creative wording.
- Use retrieved or provided facts for concrete product, customer, metric, roadmap, date, capability, and competitive claims, and cite those claims.
- Do not invent specific names, first-party data claims, metrics, roadmap status, customer outcomes, or product capabilities to make the draft sound stronger.
- If there is little or no citable support, write a useful generic draft with placeholders or clearly labeled assumptions rather than unsupported specifics.
フロントエンド開発と視覚的なセンス
フロントエンドの作業では、UI の品質を高める具体的な指示方法として、指示の例を参照してください。プロダクトとユーザーの背景、デザインシステムとの整合性、最初に表示される画面の使いやすさ、使い慣れた操作要素、想定される状態、レスポンシブな動作を扱っています。また、ありきたりなヒーローセクション、入れ子のカード、装飾的なグラデーション、画面に残った指示文、崩れたレイアウトなど、生成された UI にありがちな避けるべきパターンも取り上げています。
モデル自身による作業結果の確認
検証できる場合は、GPT-5.5 が出力を確認できるツールを使えるようにしてください。
コーディングエージェントには、具体的な検証コマンドを求めてください:
After making changes, run the most relevant validation available:
- targeted unit tests for changed behavior
- type checks or lint checks when applicable
- build checks for affected packages
- a minimal smoke test when full validation is too expensive
If validation cannot be run, explain why and describe the next best check.
視覚的な成果物については、レンダリング後の確認を求めてください:
Render the artifact before finalizing. Inspect the rendered output for layout, clipping, spacing, missing content, and visual consistency. Revise until the rendered output matches the requirements.
エンジニアリングや計画のタスクでは、実装計画の根拠を追跡できるようにしてください:
For implementation plans, include:
- requirements and where each is addressed
- named resources, files, APIs, or systems involved
- state transitions or data flow where relevant
- validation commands or checks
- failure behavior
- privacy and security considerations
- open questions that materially affect implementation
phase パラメータ
GPT-5.4 以降では、長時間実行する、またはツールを多用する Responses ワークフローで、アシスタント項目の phase 値を使い、途中経過の報告と最終回答を区別できます。GPT-5.5 でも同じパターンを使います。
previous_response_id を使う場合、API がそれまでのアシスタントの状態を自動的に保持します。アプリケーション側でアシスタントの出力項目を次のリクエストに再送する場合は、各項目の元の phase 値を保持し、変更せずに渡してください。これは、応答に前置きや繰り返しのツール呼び出しが含まれる場合、またはアシスタントによる途中経過の報告の後に最終回答が続く場合に、特に重要です。
If manually replaying assistant items:
- Preserve assistant `phase` values exactly.
- Use `phase: "commentary"` for intermediate user-visible updates.
- Use `phase: "final_answer"` for the completed answer.
- Do not add `phase` to user messages.
おすすめのプロンプト構成
複雑なプロンプトを作成する際は、この構成を出発点にしてください。各セクションは短くまとめ、動作に影響する部分にだけ詳細を追加します。
Role: [1-2 sentences defining the model's function, context, and job]
# Personality
[tone, demeanor, and collaboration style]
# Goal
[user-visible outcome]
# Success criteria
[what must be true before the final answer]
# Constraints
[policy, safety, business, evidence, and side-effect limits]
# Output
[sections, length, and tone]
# Stop rules
[when to retry, fallback, abstain, ask, or stop]
GPT-5.4 の使用
GPT-5.4 と GPT-5.4 モデルファミリーのベストプラクティス、機能、移行の指針を紹介します。
はじめに
GPT-5.4 は、API と Codex で専門的な業務に対応するフロンティアモデルとしてリリースされました。複雑な情報の分析、本番用ソフトウェアの開発、複数ステップのワークフローの自動化を支援します。
GPT-5.4 世代の中で、gpt-5.4 はソフトウェアエンジニアリング、推論、文章作成、ツールの使用を組み合わせるワークフロー向けの汎用モデルです。
このガイドでは、GPT-5 モデルファミリーの主な機能と、GPT-5.4 を最大限に活用する方法を紹介します。
新着情報
GPT-5.4 は、従来の GPT-5.2 モデルと比べて、次の点が向上しています。
- コーディング、ドキュメントの理解、ツールの使用、指示への追従
- 画像認識とマルチモーダルタスク
- 長時間にわたるタスクの実行と、複数ステップのエージェントワークフロー
- ツールを多用するワークロードでのトークン効率と処理全体のパフォーマンス
- 見つけにくい情報を探すためのウェブ検索と、複数の情報源を統合する能力
- カスタマーサービス、分析、財務における、ドキュメントやスプレッドシートを多用する業務ワークフロー
GPT-5.4 は、OpenAI のフラッグシップであるフロンティアモデルに GPT-5.3-Codex のコーディング能力を取り入れています。開発者は、本番環境で使える品質のコードの生成、洗練されたフロントエンド UI の構築、リポジトリ固有のパターンへの準拠、複数ファイルにまたがる変更を、より少ない再試行で行えます。また、初期状態からコーディングに適した優れたパーソナリティを備えているため、チームがプロンプトの調整に費やす時間を減らせます。
エージェント型のワークロードでは、GPT-5.4 は複数ステップにわたる一連の処理の所要時間を短縮し、多くの場合、より少ないトークンとツール呼び出しでタスクを完了します。これによりエージェントの応答性が向上し、API と Codex で複雑なワークフローを大規模に運用するコストを削減できます。
GPT-5.4 の新機能
GPT-5.4 は、以前の GPT-5 モデルと同様に、カスタムツール、詳細度や推論を制御するパラメーター、許可されたツールのリストをサポートしています。さらに、高度なエージェントシステムの構築、より大量の情報の処理、より信頼性の高い自動化ワークフローの実行を容易にする、次のような機能も導入しています。
- API の
tool_search: GPT-5.4 は、ツールの遅延読み込みによって、大規模なツールエコシステムでのツール検索を改善しています。ツールを検索可能にし、関連する定義だけを読み込むことで、トークン使用量を削減し、実際の運用環境でのツール選択精度を高めます。詳しくは、ツール検索ガイドをご覧ください。 - 1M トークンのコンテキストウィンドウ: GPT-5.4 は最大 1M トークンのコンテキストウィンドウをサポートし、コードベース全体、大量の長文ドキュメント、長期にわたるエージェントの実行履歴を、単一のリクエストで分析しやすくします。詳しくは、1M コンテキストウィンドウのセクションをご覧ください。
- コンピューターの使用機能を内蔵: GPT-5.4 は、コンピューターの使用機能を内蔵した初の主力モデルです。エージェントがソフトウェアを直接操作し、構築、実行、検証、修正のループを通じてタスクを完了、検証、修正できます。詳しくは、コンピューターの使用ガイドをご覧ください。
- コンパクションのネイティブサポート: GPT-5.4 は、コンパクションをサポートするように学習された初の主力モデルです。重要なコンテキストを保持しながら、エージェントがより長い一連の処理を実行できます。
モデル、API、機能の更新
この世代では、gpt-5.4 が幅広いタスクとコーディングの両方に対応する汎用モデルです。より難しい問題には、gpt-5.4-pro がより多くの計算リソースを使って長く思考し、より一貫性のある回答を提供します。
より小型で高速なモデルを求める場合は、まず gpt-5.4-mini または gpt-5.4-nano をお試しください。
用途に最適なモデルを選ぶ際は、次のトレードオフを考慮してください。
| バリエーション | 最適な用途 |
|---|---|
gpt-5.4 | 複雑な推論、世界に関する幅広い知識の活用、コードを多用するタスクや複数ステップのエージェント型タスクなど、汎用的な業務 |
gpt-5.4-pro | 解決に時間がかかる可能性があり、より深い推論を必要とする難問 |
gpt-5.4-mini | 高度な推論能力を維持しながら大量に処理するコーディング、コンピューターの使用、エージェントワークフロー |
gpt-5.4-nano | 速度とコストを最優先する、高スループットのタスク |
より低い推論強度
reasoning.effort パラメーターは、モデルが応答を生成する前に生成する推論トークンの数を制御します。o3 などの以前のリーズニングモデルは low、medium、high のみをサポートしていました。low は速度とトークン数の削減を優先し、high はより綿密な推論を優先していました。
GPT-5.2 と GPT-5.4 は、低レイテンシーでのやり取りに向けて、最も低い推論強度として none をサポートしています。どちらのモデルでも、これがデフォルト設定です。より多くの思考が必要な場合は、medium まで段階的に引き上げ、結果を試しながら調整してください。
推論強度を none に設定した場合は、プロンプトの書き方が重要です。デフォルト設定でもモデルの推論の質を高めるには、回答する前に「考える」ことや、手順の概要を示すことを促してください。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.4",
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?",
reasoning={"effort": "none"},
)
print(response)詳細度
詳細度は、生成される出力トークンの数を決定します。トークン数を減らすと、全体のレイテンシーが下がります。モデルの推論方法はほぼ変わりませんが、より簡潔に回答するよう工夫するため、用途によって回答の質が向上する場合も、低下する場合もあります。詳細度を高く設定する場合と低く設定する場合の用途例を紹介します。
- 詳細度が高い場合: ドキュメントの詳しい説明や、広範囲にわたるコードのリファクタリングをモデルに求める場合に使用します。
- 詳細度が低い場合: 簡潔な回答や、SQL クエリなど特定の目的に絞ったコード生成を求める場合に最適です。
GPT-5 では、このオプションを high、medium、low のいずれかに設定できるようになりました。GPT-5.4 でも詳細度を設定でき、デフォルトは medium です。
GPT-5.4 でコードを生成する場合、詳細度を medium または high にすると、インラインの説明を含む、より長く構造化されたコードが生成されます。一方、low では、説明を最小限に抑えた、より短く簡潔なコードが生成されます。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.4",
input="What is the answer to the ultimate question of life, the universe, and everything?",
text={"verbosity": "low"},
)
print(response)API で詳細度を low に設定した後も、プロンプトで詳細度を調整できます。詳細度パラメーターはシステムプロンプトのレベルでおおよそのトークン数の範囲を定めますが、実際の出力は、その範囲内で開発者とユーザーの両方のプロンプトに柔軟に対応します。
1M コンテキストウィンドウ
GPT-5.4 では 1M トークンのコンテキストウィンドウが導入され、コードベース全体、大量の長文ドキュメント、長期にわたるエージェントの実行履歴を、単一のリクエストで分析しやすくなりました。
272K トークン未満のリクエストと 272K トークンを超えるリクエストには、それぞれ異なる標準料金が設定されています。詳しくは料金ドキュメントをご覧ください。Fast モードを使用している場合、272K トークンを超えるプロンプトはすべて自動的に標準料金で処理されます。
長いコンテキストの料金には、データレジデンシーやバッチなど、ほかの料金調整も重ねて適用されます。
272K トークン未満のリクエストと 272K トークンを超えるリクエストには、それぞれ異なるレート制限があります。詳しくは、GPT-5.4 モデルのページをご覧ください。
GPT-5.4 でのツールの使用
GPT-5.4 は、特定のツールの使用について事後学習済みです。より具体的な指針については、ツールのドキュメントをご覧ください。
コンピューターの使用ツール
コンピューターの使用により、GPT-5.4 はスクリーンショットを確認し、ハーネスが実行するための構造化されたアクションを返すことで、ユーザーインターフェイスを通じてソフトウェアを操作できます。サイト内の移動、フォームへの入力、変更が実際に機能したかどうかの検証など、人が UI を通じて完了できるブラウザやデスクトップのワークフローに適しています。
隔離されたブラウザまたは VM で使用し、影響の大きいアクションには人が関与するようにしてください。詳細ガイドでは、Responses API に組み込まれたループ、カスタムハーネスのパターン、コード実行ベースの構成について説明しています。
組み込みのコンピューターツールを安全に実行し、独自のハーネスと統合する方法を紹介します。
ツール検索ツール
ツール検索により、GPT-5.4 は多数のツール定義の読み込みを実行時まで遅らせ、必要な定義だけを読み込めます。関数、namespaces、MCP ツールが多数あり、すべてのスキーマを最初から提示せずに、トークン使用量を削減し、キャッシュ性能を維持し、レイテンシーを改善したい場合に特に有効です。
リクエスト時点で候補となるツールがわかっている場合はホスト型ツール検索を使用し、読み込むツールをアプリケーション側で動的に決める必要がある場合はクライアント実行型ツール検索を使用します。詳細ガイドでは、namespaces、MCP サーバー、遅延読み込みのベストプラクティスも紹介しています。
ツール定義の読み込みを遅らせ、実行時に必要なものだけを読み込む方法を説明します。
カスタムツール
GPT-5 モデルファミリーのリリース時に、カスタムツールという新機能を導入しました。モデルは任意の生のテキストをツール呼び出しの入力として送信でき、必要に応じて出力を制約することもできます。このツールの動作は GPT-5.4 でも変わりません。
カスタムツールについては、Function Calling ガイドをご覧ください。
自由形式の入力
ツールを type: custom で定義すると、モデルは構造化された JSON に限らず、プレーンテキストの入力をツールに直接送信できます。コード、SQL クエリ、シェルコマンド、設定ファイル、長文など、任意の生のテキストを直接ツールに送信できます。
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary python code"
}
出力の制約
GPT-5.4 はカスタムツールで文脈自由文法(CFGs)をサポートしています。Lark 文法を指定することで、出力を特定の構文や DSL に制約できます。たとえば SQL や DSL の文法を CFG として指定すると、アシスタントのテキストがその文法に従うことが保証されます。
これにより、制約に従った正確なツール呼び出しや構造化された応答が可能になります。また、GPT-5.4 の Function Calling に厳密な構文やドメイン固有の形式を直接適用できるため、複雑なドメインや制約のあるドメインでも制御性と信頼性が向上します。
カスタムツールのベストプラクティス
- ツールの説明は簡潔かつ明確に記述します。 モデルはその説明に基づいて送信する内容を選びます。常にツールを呼び出してほしい場合は、その旨を明示してください。
- サーバー側で出力を検証します。自由形式の文字列は強力ですが、インジェクションや安全でないコマンドへの対策が必要です。
許可されたツール
tool_choice 内の allowed_tools パラメーターを使うと、N 個のツール定義を渡しつつ、モデルが使用できるツールをそのうちの M(< N)個に制限できます。tools にすべてのツールを列挙し、allowed_tools ブロックで使用できるツールを指定します。さらに、モードとして auto(モデルが指定されたツールの中から自由に選択できる)または required(モデルがいずれかを必ず呼び出す)を指定します。
許可されたツールのオプションについては、Function Calling ガイドをご覧ください。
すべてのツールと、 現在使用できるツールを分けることで、安全性と予測可能性が高まり、プロンプトキャッシュの効率も向上します。また、呼び出し順序のハードコードなど、変更に弱いプロンプトエンジニアリングを避けられます。GPT-5.4 は、長いコンテキストで意図しないツールが使われるリスクを抑えながら、会話の途中で特定の関数を動的に呼び出したり、その呼び出しを必須にしたりできます。
| 標準のツール | 許可されたツール | |
|---|---|---|
| モデルが扱うツールの範囲 | "tools": […] に列挙されたすべてのツール | tool_choice 内の "tools": […] に指定されたツールのみ |
| ツールの呼び出し | モデルは任意のツールを呼び出すことも、何も呼び出さないこともできます | モデルが呼び出せるツールを指定されたものに制限します(または、その呼び出しを必須にします) |
| 目的 | 利用可能な機能の宣言 | 実際に使用する機能の制限 |
{
"tool_choice": {
"type": "allowed_tools",
"mode": "auto",
"tools": [
{ "type": "function", "name": "get_weather" },
{ "type": "function", "name": "search_docs" }
]
}
}
これらの新機能の詳細については、GPT-5.4 のプロンプトガイダンスをご覧ください。
前置き
前置きとは、GPT-5.4 がツールや関数を呼び出す前に生成する、ユーザー向けの短い説明です。「このツールを呼び出す理由」など、意図や計画の概要を示します。思考の連鎖の後、実際のツール呼び出しの前に表示されるため、モデルの推論を理解してデバッグしやすくなり、動作を的確に誘導できます。
前置きによって GPT-5.4 がツール呼び出しのたびに考えを言葉にすることで、推論のオーバーヘッドを膨らませずに、ツール呼び出しの精度とタスク全体の成功率を高められます。前置きを有効にするには、システム指示または開発者指示を追加します。たとえば、「ツールを呼び出す前に、その理由を説明してください」と指定します。GPT-5.4 は、指定された各ツール呼び出しに簡潔な理由を添えます。また、モデルはツール呼び出しの合間に複数のメッセージを出力することもあります。これにより、特に推論を最小限に抑えるユースケースや低レイテンシが重要なユースケースで、対話の体験が向上します。
前置きの使い方について詳しくは、GPT-5 のプロンプト Cookbookをご覧ください。
移行クイックスタート
GPT-5.4 は Responses API と組み合わせると最も高い性能を発揮します。Responses API はターン間で推論のコンテキストを保持でき、性能の向上につながります。現在のモデルや API から移行するには、以下をご覧ください。
他のモデルから GPT-5.4 への移行
既存のプロンプトやワークフローを GPT-5.4 に移行する際は、OpenAI Docs スキルを使用してください。 このスキルは、OpenAI の公開スキルリポジトリと Codex デスクトップアプリで利用できます。
GPT-5.2 からはほぼそのまま置き換えられるはずですが、いくつか重要な変更点があります。プロンプトに加える具体的な変更については、GPT-5.4 のプロンプトガイダンスをご覧ください。
GPT-5 モデルを Responses API と組み合わせると、API の設計により応答性能が向上します。Responses API は前のターンの CoT をモデルに渡せます。これにより、生成される推論トークンが減り、キャッシュヒット率が上がり、レイテンシが低下します。詳しくは、Responses API のメリットを解説した詳細ガイドをご覧ください。
旧世代の OpenAI モデルから GPT-5.4 に移行する際は、まず推論レベルとプロンプトの戦略を試してみてください。プロンプト最適化ツールを使って、最新のベストプラクティスに基づいてプロンプトを GPT-5.4 向けに更新し、以下のモデル別ガイダンスに従ってください。
gpt-5.2:デフォルト設定のgpt-5.4は、そのまま置き換えて使えるように設計されています。- o3:推論強度を
mediumまたはhighに設定したgpt-5.4を使用します。まずmediumでプロンプトを調整し、望む結果が得られない場合はhighに引き上げてください。 gpt-4.1:推論強度をnoneに設定したgpt-5.4を使用します。まずnoneでプロンプトを調整し、さらに性能を高める必要があれば推論強度を引き上げてください。o4-miniまたはgpt-4.1-mini:プロンプトを調整したgpt-5.4-miniが優れた移行先になります。gpt-4.1-nano:プロンプトを調整したgpt-5.4-nanoが優れた移行先になります。
新しい phase パラメーター
Responses API で GPT-5.4 を使うフローが長時間にわたる場合やツールを多用する場合は、アシスタントメッセージの phase フィールドを使用して、早すぎる終了やその他の誤動作を防いでください。
phase は API 上では任意ですが、使用を強く推奨します。アシスタントの途中経過の報告(ツール呼び出し前の前置きなど)には phase: "commentary" を、完成した回答には phase: "final_answer" を使用してください。ユーザーメッセージには phase を追加しないでください。
previous_response_id を使うと、それまでのアシスタントの状態が保持されるため、
通常はこれが最も簡単な方法です。アシスタントの履歴を手動で再送する場合は、
それぞれの元の phase の値を保持してください。
これらのワークフローで phase が未指定だったり途中で失われたりすると、前置きが最終回答として扱われることがあります。
追加のガイダンスと例については、GPT-5.4
プロンプトガイドをご覧ください。
import OpenAI from "openai";
const client = new OpenAI();
const response = await client.responses.create({
model: "gpt-5.4",
input: [
{
role: "assistant",
phase: "commentary",
content:
"I’ll inspect the logs and then summarize root cause and remediation.",
},
{
role: "assistant",
phase: "final_answer",
content: "Root cause: cache invalidation race.",
},
{
role: "user",
content: "Great—now give me a rollout-safe fix plan.",
},
],
});
console.log(response.output_text);GPT-5.4 のパラメーター互換性
以下のパラメーターは、GPT-5.4 の推論強度を none に設定した場合に のみサポートされます 。
temperaturetop_plogprobs
これらのフィールドを含むリクエストは、GPT-5.4 または GPT-5.2 でそれ以外の推論強度を設定した場合や、gpt-5、gpt-5-mini、gpt-5-nano などの旧世代の GPT-5 モデルを使用した場合にエラーになります。
推論強度をより高く設定した場合や、GPT-5 ファミリーの別のモデルを使用する場合に同様の結果を得るには、代わりに以下のパラメーターを試してください。
- 推論の深さ:
reasoning: { effort: "none" | "low" | "medium" | "high" | "xhigh" } - 出力の詳細度:
text: { verbosity: "low" | "medium" | "high" } - 出力の長さ:
max_output_tokens
Chat Completions から Responses API への移行
GPT-5.4 で Chat Completions から Responses API に移行する最大の理由であり、両者の最も大きな違いは、ターン間で思考の連鎖(CoT)を引き継げることです。詳しくは、API の比較をご覧ください。
CoT の引き継ぎに対応しているのは Responses API のみです。これにより、応答性能の向上、生成される推論トークンの削減、キャッシュヒット率の向上、レイテンシの短縮が確認されています。他のほとんどのパラメーターは、形式こそ異なるものの、同等の機能を備えています。新しいパラメーターの扱いが Chat Completions と Responses API でどう異なるかを以下に示します。
推論強度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
"reasoning": {
"effort": "none"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
}
],
"reasoning_effort": "none"
}'詳細度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "What is the answer to the ultimate question of life, the universe, and everything?",
"text": {
"verbosity": "low"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "What is the answer to the ultimate question of life, the universe, and everything?"
}
],
"verbosity": "low"
}'カスタムツール
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"input": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry",
"tools": [
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
]
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.4",
"messages": [
{
"role": "user",
"content": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry"
}
],
"tools": [
{
"type": "custom",
"custom": {
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
}
]
}'プロンプトのベストプラクティス
GPT-5.4 が途中の進捗報告を最終回答として扱う問題を調べる際は、
実装でアシスタントメッセージの phase フィールドが正しく保持されているか確認してください。
詳しくは、Phase パラメーターをご覧ください。
GPT-5.4 の動作の理解
GPT-5.4 が特に得意とする領域
GPT-5.4 は、特に以下の領域で優れた性能を発揮する傾向があります。
- 指定されたパーソナリティやトーンへの高い忠実度と、長い回答でもぶれにくい一貫性
- 複数ステップの作業を粘り強く進め、再試行しながらエージェントの処理ループを最後まで完遂する、エージェント型ワークフローの堅牢性
- 特に長いコンテキストや複数のツールを使うワークフローでの、豊富な根拠に基づく情報の統合
- 要件が明示されている場合の、モジュール化されたプロンプト、スキルベースのプロンプト、ブロック構造のプロンプトにおける指示の遵守
- 大量の入力、整理されていない入力、複数の文書にまたがる入力を対象とした、長いコンテキストの分析
- 呼び出しの正確さを維持した、ツールのバッチ呼び出しや並列呼び出し
- 指示の遵守、書式の忠実な再現、より厳密な自己検証が求められる、スプレッドシート、財務、Excel のワークフロー
引き続き明示的なプロンプトが有効な場面
こうした強みがあっても、よく見られる以下の場面では、GPT-5.4 により明確な指示を与えると効果的です。
- コンテキストがまだ少なく、ツール選択の信頼性が下がることのあるセッション初期のツール振り分け
- 前提条件や後続ステップの明示的な確認が必要な、依存関係を考慮したワークフロー
- 高ければよいとは限らず、直感ではなくタスクの特性に応じて適切に選ぶ必要がある推論強度の設定
- 規律ある情報源の収集と、一貫した出典の明示が求められるリサーチタスク
- 実行前の検証が必要な、取り消せない操作や影響の大きい操作
- ツールの役割と使用範囲を明確に保つ必要があるターミナル環境やコーディングエージェント環境
これらはデフォルトで観察された傾向であり、動作を保証するものではありません。まずは評価に合格する最小限のプロンプトから始め、測定で確認された失敗パターンを解消する場合にのみブロックを追加してください。
基本的なプロンプトパターンの活用
簡潔で構造化された出力
GPT-5.4 のトークン効率を高めるには、出力要件を明確に定めて詳細度を制限し、構造化出力を徹底してください。これは実質的に、Responses API の verbosity パラメーターを補う制御として機能し、モデルが書く量と出力の構造の両方を指定できます。
<output_contract>
- Return exactly the sections requested, in the requested order.
- If the prompt defines a preamble, analysis block, or working section, do not treat it as extra output.
- Apply length limits only to the section they are intended for.
- If a format is required (JSON, Markdown, SQL, XML), output only that format.
</output_contract>
<verbosity_controls>
- Prefer concise, information-dense writing.
- Avoid repeating the user's request.
- Keep progress updates brief.
- Do not shorten the answer so aggressively that required evidence, reasoning, or completion checks are omitted.
</verbosity_controls>
タスク遂行に関する明確な基本方針の設定
ユーザーは会話の途中でタスク、形式、トーンを変更することがよくあります。アシスタントがユーザーの意図に沿って動作し続けるよう、いつ作業を進め、いつ質問し、新しい指示を以前の基本方針よりどのように優先するかを明確に定めてください。
タスクを最後まで進めるための基本方針として、次のようなものを使用します。
<default_follow_through_policy>
- If the user’s intent is clear and the next step is reversible and low-risk, proceed without asking.
- Ask permission only if the next step is:
(a) irreversible,
(b) has external side effects (for example sending, purchasing, deleting, or writing to production), or
(c) requires missing sensitive information or a choice that would materially change the outcome.
- If proceeding, briefly state what you did and what remains optional.
</default_follow_through_policy>
指示の優先順位を明示します。
<instruction_priority>
- User instructions override default style, tone, formatting, and initiative preferences.
- Safety, honesty, privacy, and permission constraints do not yield.
- If a newer user instruction conflicts with an earlier one, follow the newer instruction.
- Preserve earlier instructions that do not conflict.
</instruction_priority>
優先順位の高い開発者指示やシステム指示には、引き続き従う必要があります。
指針: 会話の途中で指示を変更するときは、変更内容と適用範囲を明示し、必要な箇所に限定します。何が変わり、何が引き続き適用されるのか、また変更が次のターンだけに適用されるのか、以降の会話全体に適用されるのかを示します。
会話途中の指示変更への対応
会話の途中で指示を更新するときは、次の点を明示し、適用範囲を限定したメッセージで方向性を伝えます。
- 適用範囲
- 上書きする内容
- 引き継ぐ内容
<task_update>
For the next response only:
- Do not complete the task.
- Only produce a plan.
- Keep it to 5 bullets.
All earlier instructions still apply unless they conflict with this update.
</task_update>
タスク自体が変わる場合は、そのことを明確に伝えます。
<task_update>
The task has changed.
Previous task: complete the workflow.
Current task: review the workflow and identify risks only.
Rules for this turn:
- Do not execute actions.
- Do not call destructive tools.
- Return exactly:
1. Main risks
2. Missing information
3. Recommended next step
</task_update>
正確性の確保に必要なツール利用の継続
明確なルールを設けて、依存関係を考慮しながら、適切なペースでツールを十分に活用するようにします。特に、後のアクションが先行する情報取得や検証に依存するワークフローでは重要です。よくある失敗は、正しい最終状態が明らかに思えるために、前提となる手順を省略してしまうことです。
セッションの初期段階でコンテキストがまだ少ないときは、GPT-5.4 のツール選択の信頼性が低下することがあります。前提条件、依存関係の確認、ツールを使う具体的な目的をプロンプトで指示します。
<tool_persistence_rules>
- Use tools whenever they materially improve correctness, completeness, or grounding.
- Do not stop early when another tool call is likely to materially improve correctness or completeness.
- Keep calling tools until:
(1) the task is complete, and
(2) verification passes (see <verification_loop>).
- If a tool returns empty or partial results, retry with a different strategy.
</tool_persistence_rules>
これは、最終的なアクションが先行する検索や情報取得の手順に依存するワークフローで特に重要です。最もよくある失敗の一つは、目指す最終状態が明らかに思えるために、前提となる手順を省略してしまうことです。
<dependency_checks>
- Before taking an action, check whether prerequisite discovery, lookup, or memory retrieval steps are required.
- Do not skip prerequisite steps just because the intended final action seems obvious.
- If the task depends on the output of a prior step, resolve that dependency first.
</dependency_checks>
作業が互いに独立していて、実際の所要時間を重視する場合は、並列実行を指示します。速度よりも依存関係、曖昧さ、取り消せないアクションへの対処を重視する場合は、順次実行を指示します。
<parallel_tool_calling>
- When multiple retrieval or lookup steps are independent, prefer parallel tool calls to reduce wall-clock time.
- Do not parallelize steps that have prerequisite dependencies or where one result determines the next action.
- After parallel retrieval, pause to synthesize the results before making more calls.
- Prefer selective parallelism: parallelize independent evidence gathering, not speculative or redundant tool use.
</parallel_tool_calling>
長期タスクの完全な実行の徹底
複数のステップからなるワークフローでは、不完全な実行がよくある失敗です。モデルが対象の一部だけを処理して終了したり、バッチ内の項目を見落としたり、空の取得結果や範囲の狭い取得結果を最終結果として扱ったりします。プロンプトで完了条件と復旧時の動作を明確に定義すると、GPT-5.4 の信頼性が向上します。
情報取得を順次実行しても並列実行しても、対象範囲を網羅できます。ただし、どちらの場合も完了条件を明示する必要があります。
<completeness_contract>
- Treat the task as incomplete until all requested items are covered or explicitly marked [blocked].
- Keep an internal checklist of required deliverables.
- For lists, batches, or paginated results:
- determine expected scope when possible,
- track processed items or pages,
- confirm coverage before finalizing.
- If any item is blocked by missing data, mark it [blocked] and state exactly what is missing.
</completeness_contract>
取得結果が空、不完全、またはノイズを含むことが多いワークフローでは、次のように指示します。
<empty_result_recovery>
If a lookup returns empty, partial, or suspiciously narrow results:
- do not immediately conclude that no results exist,
- try at least one or two fallback strategies,
such as:
- alternate query wording,
- broader filters,
- a prerequisite lookup,
- or an alternate source or tool,
- Only then report that no results were found, along with what you tried.
</empty_result_recovery>
影響の大きいアクションの前に行う検証ループの追加
ワークフローが完了したように見えても、回答を返したり取り消せないアクションを実行したりする前に、簡単な検証ステップを設けます。これにより、確定する前に、要件の見落とし、グラウンディングの問題、形式のずれを検出しやすくなります。
<verification_loop>
Before finalizing:
- Check correctness: does the output satisfy every requirement?
- Check grounding: are factual claims backed by the provided context or tool outputs?
- Check formatting: does the output match the requested schema or style?
- Check safety and irreversibility: if the next step has external side effects, ask permission first.
</verification_loop>
<missing_context_gating>
- If required context is missing, do NOT guess.
- Prefer the appropriate lookup tool when the missing context is retrievable; ask a minimal clarifying question only when it is not.
- If you must proceed, label assumptions explicitly and choose a reversible action.
</missing_context_gating>
実際にアクションを実行するエージェントには、簡潔な実行の枠組みを追加します。
<action_safety>
- Pre-flight: summarize the intended action and parameters in 1-2 lines.
- Execute via tool.
- Post-flight: confirm the outcome and any validation that was performed.
</action_safety>
専門的なワークフローへの対応
視覚認識とコンピューターの使用における画像の詳細度の明示的な選択
視覚的な精度が必要なワークフローでは、auto に任せず、プロンプトまたは連携実装で画像の detail レベルを指定します。標準的な高精度の画像理解には high を使用します。大きな画像、情報密度の高い画像、位置関係の正確な把握が必要な画像には original を使用します。特に、gpt-5.4 および今後のモデルで行うコンピューターの使用、位置特定、OCR、クリック精度が求められるタスクで有効です。細部の把握よりも速度とコストを重視する場合にのみ、low を使用します。画像の詳細度レベルについて詳しくは、画像と視覚認識ガイドを参照してください。
取得した根拠に限定したリサーチと引用
引用の品質が重要な場合は、利用できる情報源の範囲と形式の要件を両方とも明示します。これにより、架空の参考文献、裏付けのない主張、引用形式のずれを減らせます。
<citation_rules>
- Only cite sources retrieved in the current workflow.
- Never fabricate citations, URLs, IDs, or quote spans.
- Use exactly the citation format required by the host application.
- Attach citations to the specific claims they support, not only at the end.
</citation_rules>
<grounding_rules>
- Base claims only on provided context or tool outputs.
- If sources conflict, state the conflict explicitly and attribute each side.
- If the context is insufficient or irrelevant, narrow the answer or say you cannot support the claim.
- If a statement is an inference rather than a directly supported fact, label it as an inference.
</grounding_rules>
アプリケーションで本文中の引用が必要なら、その形式を必須とします。脚注が必要なら、脚注を必須とします。重要なのは、形式を固定し、モデルが裏付けのない参考文献をその場で作り出さないようにすることです。
リサーチモード
GPT-5.4 が規律ある手順でリサーチを行うように指示します。このパターンは、リサーチ、レビュー、情報の統合を行うタスクに使用します。短い実行タスクや単純な決定論的変換には、無理に適用しないでください。
<research_mode>
- Do research in 3 passes:
1) Plan: list 3-6 sub-questions to answer.
2) Retrieve: search each sub-question and follow 1-2 second-order leads.
3) Synthesize: resolve contradictions and write the final answer with citations.
- Stop only when more searching is unlikely to change the conclusion.
</research_mode>
ホスト環境で特定のリサーチツールを使用している場合や、提出ステップが必要な場合は、このパターンをホスト側の完了処理の規約と組み合わせます。
厳密な出力形式の徹底
SQL、JSON など、解析のために正確な形式が求められる出力では、指定の形式だけを出力し、終了前に確認するよう GPT-5.4 に指示します。
<structured_output_contract>
- Output only the requested format.
- Do not add prose or markdown fences unless they were requested.
- Validate that parentheses and brackets are balanced.
- Do not invent tables or fields.
- If required schema information is missing, ask for it or return an explicit error object.
</structured_output_contract>
文書内の領域や OCR ボックスを抽出する場合は、座標系を定義し、ずれを確認する処理を追加します。
<bbox_extraction_spec>
- Use the specified coordinate format exactly, such as [x1,y1,x2,y2] normalized to 0..1.
- For each box, include page, label, text snippet, and confidence.
- Add a vertical-drift sanity check so boxes stay aligned with the correct line of text.
- If the layout is dense, process page by page and do a second pass for missed items.
</bbox_extraction_spec>
コーディングエージェントとターミナルエージェントにおけるツールの役割分担の明示
コーディングエージェントでは、シェルへのアクセスとファイル編集のルールが明確なほど、GPT-5.4 はより適切に動作します。これは、シェルやパッチの適用などのツールを利用可能にする場合に特に重要です。
ユーザーへの進捗報告
GPT-5.4 は、成果を中心とした短い進捗報告を得意としています。5.2 ガイドのユーザーへの進捗報告パターンを再利用し、完了と検証に関する明確な要件を組み合わせます。
進捗報告に推奨される仕様は次のとおりです。
<user_updates_spec>
- Only update the user when starting a new major phase or when something changes the plan.
- Each update: 1 sentence on outcome + 1 sentence on next step.
- Do not narrate routine tool calls.
- Keep the user-facing status short; keep the work exhaustive.
</user_updates_spec>
コーディングエージェントについての詳しい指針は、以下の「コーディングタスク向けのプロンプトパターン」を参照してください。
コーディングタスク向けのプロンプトパターン
自律性と継続性
GPT-5.4 は、コーディングやツール利用のタスクを、従来の主力モデルよりも概して最初から最後まで入念に実行します。そのため、「すべてを検証する」といった明示的な指示は、多くの場合、以前ほど必要ありません。ただし、本番環境、移行、セキュリティ作業など、重大な影響を及ぼす変更では、簡潔な検証の指示を残してください。
<autonomy_and_persistence>
Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
Unless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.
</autonomy_and_persistence>
作業途中の進捗報告
進捗報告の頻度は抑え、重要な情報に絞ります。コーディングタスクでは、要所で報告するようにします。
<user_updates_spec>
- Intermediary updates go to the `commentary` channel.
- User updates are short updates while you are working. They are not final answers.
- Use 1-2 sentence updates to communicate progress and new information while you work.
- Do not begin responses with conversational interjections or meta commentary. Avoid openers such as acknowledgements ("Done -", "Got it", or "Great question") or similar framing.
- Before exploring or doing substantial work, send a user update explaining your understanding of the request and your first step. Avoid commenting on the request or starting with phrases such as "Got it" or "Understood."
- Provide updates roughly every 30 seconds while working.
- When exploring, explain what context you are gathering and what you learned. Vary sentence structure so the updates do not become repetitive.
- When working for a while, keep updates informative and varied, but stay concise.
- When work is substantial, provide a longer plan after you have enough context. This is the only update that may be longer than 2 sentences and may contain formatting.
- Before file edits, explain what you are about to change.
- While thinking, keep the user informed of progress without narrating every tool call. Even if you are not taking actions, send frequent progress updates rather than going silent, especially if you are thinking for more than a short stretch.
- Keep the tone of progress updates consistent with the assistant's overall personality.
</user_updates_spec>
書式
GPT-5.4 は、特に指定がないと構造化された書式を使う傾向があり、箇条書きを多用することがあります。すっきりした最終回答が必要なら、リストの形式を明示的に制限します。
Never use nested bullets. Keep lists flat (single level). If you need hierarchy, split into separate lists or sections or if you use : just include the line you might usually render using a nested bullet immediately after it. For numbered lists, only use the `1. 2. 3.` style markers (with a period), never `1)`.
フロントエンドのタスク
フロントエンド向けの追加の指針が役立つ場合にのみ使用します。
<frontend_tasks>
When doing frontend design tasks, avoid generic, overbuilt layouts.
Use these hard rules:
- One composition: The first viewport must read as one composition, not a dashboard, unless it is a dashboard.
- Brand first: On branded pages, the brand or product name must be a hero-level signal, not just nav text or an eyebrow. No headline should overpower the brand.
- Brand test: If the first viewport could belong to another brand after removing the nav, the branding is too weak.
- Full-bleed hero only: On landing pages and promotional surfaces, the hero image should usually be a dominant edge-to-edge visual plane or background. Do not default to inset hero images, side-panel hero images, rounded media cards, tiled collages, or floating image blocks unless the existing design system clearly requires them.
- Hero budget: The first viewport should usually contain only the brand, one headline, one short supporting sentence, one CTA group, and one dominant image. Do not place stats, schedules, event listings, address blocks, promos, "this week" callouts, metadata rows, or secondary marketing content there.
- No hero overlays: Do not place detached labels, floating badges, promo stickers, info chips, or callout boxes on top of hero media.
- Cards: Default to no cards. Never use cards in the hero unless they are the container for a user interaction. If removing a border, shadow, background, or radius does not hurt interaction or understanding, it should not be a card.
- One job per section: Each section should have one purpose, one headline, and usually one short supporting sentence.
- Real visual anchor: Imagery should show the product, place, atmosphere, or context.
- Reduce clutter: Avoid pill clusters, stat strips, icon rows, boxed promos, schedule snippets, and competing text blocks.
- Use motion to create presence and hierarchy, not noise. Ship 2-3 intentional motions for visually led work, and prefer Framer Motion when it is available.
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
</frontend_tasks>
<terminal_tool_hygiene>
- Only run shell commands via the terminal tool.
- Never "run" tool names as shell commands.
- If a patch or edit tool exists, use it directly; do not attempt it in bash.
- After changes, run a lightweight verification step such as ls, tests, or a build before declaring the task done.
</terminal_tool_hygiene>
文書内の位置特定と OCR ボックス
bbox タスクでは、座標の規約を明示し、ずれを検出するテストを追加します。
<bbox_extraction_spec>
- Use the specified coordinate format exactly (for example [x1,y1,x2,y2] normalized 0..1).
- For each bbox, include: page, label, text snippet, confidence.
- Add a vertical-drift sanity check:
- ensure bboxes align with the line of text (not shifted up or down).
- If dense layout, process page by page and do a second pass for missed items.
</bbox_extraction_spec>
ランタイムと API 連携に関する留意点の活用
長時間実行するエージェントやツールを多用するエージェントでは、ランタイムの規約がプロンプトの規約と同じくらい重要です。
フェーズパラメーター
GPT-5.4、gpt-5.3-codex、およびそれ以降の Responses モデルでは、phase フィールドが、
長時間実行するフローやツールを多用するフローの一部で役立つことがあります。こうしたフローでは、ツール実行前の説明や
その他のアシスタントによる途中経過の報告が、最終回答と誤認される場合があります。
phaseは API 上では省略可能ですが、使用を強く推奨します。サーバー側で可能な範囲での推定が行われる場合もありますが、phaseを明示的に受け渡しする方が確実に優れています。- 長時間実行するエージェントやツールを多用するエージェントで、ツール呼び出しや最終回答の前に途中経過の説明を出力する可能性がある場合は、
phaseを使用します。 - 過去のアシスタント項目を再送するときは、
phaseを保持し、モデルが作業中の説明と完成した回答を区別できるようにします。これは、ツール実行前の説明、ツールに関する進捗報告、同一ターン内の複数のアシスタントメッセージを含む、複数ステップのフローで特に重要です。 - ユーザーメッセージには
phaseを追加しないでください。 - 通常、最も簡単なのは
previous_response_idを使用する方法です。アシスタント項目を手動で再送しなくても、OpenAI 側で以前の状態を復元できることが多いためです。 - アシスタントの履歴を自分で再送する場合は、元の
phaseの値を保持します。 phaseがない場合や途中で失われた場合は、ツール実行前の説明が最終回答として解釈され、こうした複数ステップのタスクで動作の質が低下することがあります。
長いセッションでの動作の維持
コンパクションにより、実効的なコンテキストウィンドウを大幅に拡張できます。ユーザーとの会話を、コンテキストの上限や長いコンテキストによる性能低下に直面することなく、何ターンにもわたって継続できます。また、エージェントは、長時間にわたる複雑なタスクで、通常のコンテキストウィンドウを超える非常に長い処理を実行できます。
Responses API でコンパクションを使用する場合は、主要な区切りでコンパクションを実行し、圧縮された項目は内部を解釈しない状態データとして扱い、コンパクション後もプロンプトの機能が変わらないようにします。このエンドポイントは ZDR に対応しており、後続のリクエストに渡せる encrypted_content 項目を返します。GPT-5.4 は、複数ターンにわたる長い会話でも一貫性と信頼性を維持しやすく、セッションが長くなっても破綻が少ない傾向があります。
詳しくは、/responses/compact API リファレンスをご覧ください。
顧客向けワークフローのパーソナリティ制御
セッション全体で維持するパーソナリティと、応答ごとの文章作成の指定を分けると、GPT-5.4 をより効果的に誘導できます。これは、メール、サポートの返信、お知らせ、ブログ形式のコンテンツなど、顧客向けのワークフローで特に役立ちます。
- パーソナリティ(継続的): セッション全体の標準的なトーン、詳しさ、判断スタイルを設定します。
- 文章作成の指定(応答ごと): 個々の成果物について、発信媒体、文体、書式、長さを定義します。
- 注意: パーソナリティをタスク固有の出力要件より優先してはいけません。ユーザーが JSON を求めた場合は、JSON を返します。
自然で質の高い文章を得るには、次の指定が特に効果的です。
- モデルに明確なペルソナを与えます。
- 発信媒体と感情面のトーンを指定します。
- 文章での回答が必要な場合は、書式設定を明示的に禁止します。
- 長さに厳密な制限を設けます。
<personality_and_writing_controls>
- Persona: <one sentence>
- Channel: <Slack | email | memo | PRD | blog>
- Emotional register: <direct/calm/energized/etc.> + "not <overdo this>"
- Formatting: <ban bullets/headers/markdown if you want prose>
- Length: <hard limit, e.g. <=150 words or 3-5 sentences>
- Default follow-through: if the request is clear and low-risk, proceed without asking permission.
</personality_and_writing_controls>
そのまま使えるパーソナリティのパターンについては、プロンプトによるパーソナリティ設定の Cookbookをご覧ください。
業務メモ作成モード
メモ、レビュー、その他の業務文書の作成では、一般的な文章作成の指示だけでは不十分な場合がよくあります。こうしたワークフローでは、記述の具体性、分野ごとの慣例、情報の統合、根拠に見合った確信度の表現について、明示的に指示すると効果的です。
<memo_mode>
- Write in a polished, professional memo style.
- Use exact names, dates, entities, and authorities when supported by the record.
- Follow domain-specific structure if one is requested.
- Prefer precise conclusions over generic hedging.
- When uncertainty is real, tie it to the exact missing fact or conflicting source.
- Synthesize across documents rather than summarizing each one independently.
</memo_mode>
このモードは、法律、政策、リサーチ、経営層向けの文書作成で特に役立ちます。こうした文書では、流暢さだけでなく、情報を筋道立てて統合し、明確な結論を示すことが求められます。
推論の調整と移行
最終的な微調整としての推論強度
すべてのタスクに適した推論強度の設定はありません。品質改善の主な手段ではなく、最終的な微調整に使う設定として扱います。多くの場合、プロンプトの改善、明確な出力要件、簡単な検証ループによって、推論強度を上げることで得ようとしていた性能向上の大部分を実現できます。
推奨するデフォルト設定は次のとおりです。
none:モデルによる思考が不要で、速度、コスト、レイテンシを重視するタスクに最適です。low:少しの思考で精度を有意に高められる、レイテンシ重視のタスクに適しています。特に、指示が複雑な場合に効果的です。mediumまたはhigh:より高度な推論が本当に必要で、レイテンシとコストの増加を許容できるタスクに限定して使用します。推論を増やすことで対象のタスクの性能がどれだけ向上するかに基づいて、どちらを使うか選びます。xhigh:評価で明確な効果が確認できない限り、デフォルトにはしないでください。速度やコストよりも最高の知的能力を重視する、長時間にわたり多くの推論を要するエージェント型のタスクに最適です。
実際には、ほとんどのチームで none、low、medium のいずれかをデフォルトにするのが適切です。
ワークフローの各ステップ、フィールドの抽出、サポートのトリアージ、短い構造化データの変換など、実行が中心のワークロードでは none から始めます。
長いコンテキストに含まれる情報の統合、複数文書のレビュー、矛盾の解消、戦略文書の作成など、リサーチが中心のワークロードでは medium 以上から始めます。medium と適切に設計したプロンプトを組み合わせれば、高い性能を引き出せます。
GPT-5.4 のワークロードでは、アクションの選択やツール使用ルールの遵守を求めるタスクは、none でも十分な性能を発揮できます。暗黙の要件、曖昧さ、キャンセルされたツール呼び出しからの復旧など、細かなニュアンスの解釈が必要なワークロードでは、代わりに low または medium から始めます。
推論強度を上げる前に、まず次の指示を追加します。
<completeness_contract><verification_loop><tool_persistence_rules>
それでもモデルが指示を字義どおりに解釈しすぎたり、最初のもっともらしい回答で止まったりする場合は、推論強度を上げる前に、自発的に取り組むよう促す指示を追加します。
<dig_deeper_nudge>
- Don’t stop at the first plausible answer.
- Look for second-order issues, edge cases, and missing constraints.
- If the task is safety or accuracy critical, perform at least one verification step.
</dig_deeper_nudge>
一度に 1 つずつ変更する GPT-5.4 へのプロンプト移行
5.2 ガイドと同じく、一度に 1 つずつ変更する手順を守ります。まずモデルを切り替え、reasoning_effort を固定して評価を実行し、その後に改善を繰り返します。
多くの移行では、次の設定を出発点にすると効果的です。
| 現在の構成 | GPT-5.4 で推奨する初期設定 | 補足 |
|---|---|---|
gpt-5.2 | 現在と同じ推論強度 | まず既存のレイテンシと品質の特性を維持し、その後に調整します。 |
gpt-5.3-codex | 現在と同じ推論強度 | コーディングのワークフローでは、推論強度を同じに保ちます。 |
gpt-4.1 または gpt-4o | none | 素早い応答を維持し、評価結果が悪化した場合にのみ推論強度を上げます。 |
| リサーチを中心に行うアシスタント | medium または high | リサーチを複数回行うことと、引用の検証を完了条件にすることを明示的に指定します。 |
| 長期的なタスクに取り組むエージェント | medium または high | 必要なツールの使用を継続する指示と、全項目の完了状況を管理する仕組みを追加します。 |
小型モデル gpt-5.4-mini と gpt-5.4-nano の活用ガイド
gpt-5.4-mini と gpt-5.4-nano は指示による制御がしやすいモデルです。ただし、大型モデルと比べると、動作を直接指定しない限り、不足している手順を推測したり、曖昧さを暗黙に解消したり、意図した形に出力をまとめたりする可能性は低くなります。そのため、小型モデル向けのプロンプトは、やや長く、より明示的になることがよくあります。
gpt-5.4-mini の特徴
gpt-5.4-miniは指示をより字義どおりに解釈し、推測をあまり行いません。- タスクが明確に構造化されている場合は高い性能を発揮しますが、明示されていないワークフローや曖昧さへの対応は苦手です。
- 明示的に抑制しない限り、デフォルトでは追加の質問をして会話を続けようとすることがあります。
gpt-5.4-mini 向けのプロンプト
- 重要なルールを最初に記述します。
- ツールの使用や副作用が重要な場合は、実行順序をすべて指定します。
- 「必ず〜してください」と書くだけに頼らず、番号付きの手順、判断ルール、明確なアクション定義などを使って、指示を構造化します。
- 「アクションを実行すること」と「アクションを報告すること」を区別します。
- 最終的な形式だけでなく、正しい処理の流れを示します。
- 曖昧な場合の動作を明示的に定義します。どのような場合に質問し、実行を控え、またはそのまま進めるかを指定します。
- 回答の長さ、追加の質問の有無、引用形式、セクションの順序など、出力のまとめ方を直接指定します。
output nothing elseの使用には注意が必要です。after the final JSON, output nothing furtherのように、適用範囲を限定した指示を使うことをおすすめします。
gpt-5.4-nano 向けのプロンプト
gpt-5.4-nanoは、範囲が狭く、明確に限定されたタスクにのみ使用してください。- ラベル、列挙値、短い JSON、固定テンプレートなど、選択肢や形式を限定した出力を優先してください。
- 処理の流れが厳密に制限されている場合を除き、複数ステップのオーケストレーションは避けてください。
- 曖昧なタスクや入念な計画が必要なタスクは、
gpt-5.4-nanoに過剰な指示を与えて対応させるのではなく、より高性能なモデルに任せてください。
推奨する基本パターン
- タスク
- 重要なルール
- 正確な手順の順序
- エッジケースや確認が必要な場合の対応
- 出力形式
- 正しい例を 1 つ
避けるべきこと
- 次の手順を明示せず、推測に任せること
- エッジケースを未定義のままにすること
- ツールを使うワークフローに対してスキーマだけを示すプロンプト
- 構造化されていない一般的な指示
ウェブ検索と deep research
特にリサーチエージェントを移行する場合は、推論強度を上げる前に、プロンプトを次のように更新してください。
<research_mode>を追加<citation_rules>を追加<empty_result_recovery>を追加reasoning_effortを 1 段階上げるのは、プロンプトを修正してからにしてください。
5.2 のリサーチ用ブロックを出発点として、必要に応じて引用の検証条件や完了時に満たすべき要件を追加できます。
GPT-5.4 は、複数ステップでの根拠収集、長いコンテキストの情報統合、プロンプトで明示した要件への対応が必要なタスクで、特に優れた性能を発揮します。実際に効果が高いプロンプトの変更は、タスクの性質に合わせた推論強度の選択、出力形式と引用形式の厳密な定義、依存関係を考慮したツール使用ルールの追加、完了条件の明確化です。このモデルは特別な調整なしでも高い性能を発揮することが多いものの、検索方法、検証方法、何をもって完了とするかをプロンプトで明確に指定すると、最も安定して動作します。
次のステップ
- モデルの機能、パラメーター、API 互換性の詳細については、モデル、API、機能の更新を確認してください。
- モデルファミリーを問わず適用できる、より幅広いプロンプト戦略については、プロンプトエンジニアリングを参照してください。
- Responses API で長時間にわたる GPT-5.4 セッションを構築する場合は、コンパクションを参照してください。
参考資料
GPT-5.3-Codex の使い方
GPT-5.3-Codex のベストプラクティス、機能、移行方法を紹介します。
はじめに
GPT-5.3-Codex は、エージェント型コーディングにおける知能と効率の最前線をさらに押し広げます。このモデルの性能を最大限に引き出すために、本ガイドに沿って進めてください。本ガイドは、カスタマイズの自由度を最大限に確保するため、API 経由でモデルを直接利用する方を対象としています。より簡単に組み込める Codex SDK も用意しています。
API では、Codex 向けに調整されたモデルは gpt-5.3-codex です(モデルのページを参照)。
新着情報
- 速度とトークン効率の向上:より少ない思考トークンでタスクを完了します。知能と速度のバランスが取れた、幅広い対話型コーディングに適した設定として、推論強度「medium」をおすすめします。
- 知能の向上と長時間の自律動作:Codex は、特に難しいタスクを完了するために、数時間にわたって自律的に作業できます。最も難しいタスクには、推論強度
highまたはxhighを使用できます。 - コンパクションの標準サポート:コンパクションにより、コンテキストの上限に達することなく数時間にわたる推論が可能になります。また、新しいチャットセッションを始めることなく、ユーザーとの会話をより長く続けられます。
- PowerShell や Windows 環境での Codex の性能も大幅に向上しています。
移行クイックスタート
すでに動作している Codex の実装があれば、比較的少ない更新でこのモデルを問題なく利用できるはずです。一方、GPT-5 シリーズやサードパーティのモデル向けに最適化されたプロンプトとツール群を使っている場合は、より大幅な変更をおすすめします。最も参考になる実装は、GitHub で公開している完全オープンソースの codex-cli エージェントです。このリポジトリをクローンし、Codex(または任意のコーディングエージェント)に実装の仕組みを質問してみてください。また、お客様との取り組みを通じて、この実装にとどまらないエージェントハーネスのカスタマイズ方法についても知見を得ています。
ハーネスを codex-cli に移行するための主な手順は次のとおりです。
プロンプトの更新:可能であれば、標準の Codex-Max プロンプトをベースにして、必要な箇所に絞って指示を追加してください。
特に重要なのは、自律性と粘り強さ、コードベースの探索、ツールの使用、フロントエンドの品質に関するスニペットです。
また、実行開始時の計画や前置き、実行中のその他の状況報告をモデルに求める指示は、すべて削除してください。こうした指示により、一連の実行が完了する前にモデルが突然停止することがあります。
提供している
apply_patchの実装や、以下のその他のベストプラクティスを取り入れて、 ツールを更新してください。これは、性能を最大限に引き出すうえで大きな効果があります。
モデル、API、機能の更新
gpt-5.3-codexは、Codex や同様の環境でのエージェント型コーディングタスクに最適化されています。- Responses API で利用できます。
reasoning.effortは、low、medium、high、xhighをサポートしています。- サポートされているツールには、Function Calling、ウェブ検索、ホスト型シェル、スキルがあります。
プロンプトのベストプラクティス
推奨の開始用プロンプト
このプロンプトは、標準の GPT-5.1-Codex-Max プロンプトを出発点とし、回答の正確性、完全性、品質、適切なツール使用と並列実行、行動を優先する姿勢について、社内評価に基づいてさらに最適化したものです。このモデルを評価する場合は、自律性を高めるか、「非対話型」モードをプロンプトで指定することをおすすめします。ただし、実際の利用では、ユーザーへの確認を増やす方が望ましい場合もあります。
You are Codex, based on GPT-5. You are running as a coding agent in the Codex CLI on a user's computer.
# General
- When searching for text or files, prefer using `rg` or `rg --files` respectively because `rg` is much faster than alternatives like `grep`. (If the `rg` command is not found, then use alternatives.)
- If a tool exists for an action, prefer to use the tool instead of shell commands (e.g `read_file` over `cat`). Strictly avoid raw `cmd`/terminal when a dedicated tool exists. Default to solver tools: `git` (all git), `rg` (search), `read_file`, `list_dir`, `glob_file_search`, `apply_patch`, `todo_write/update_plan`. Use `cmd`/`run_terminal_cmd` only when no listed tool can perform the action.
- When multiple tool calls can be parallelized (e.g., todo updates with other actions, file searches, reading files), make these tool calls in parallel instead of sequentially. Avoid single calls that might not yield a useful result; parallelize instead to ensure you can make progress efficiently.
- Code chunks that you receive (via tool calls or from user) may include inline line numbers in the form "Lxxx:LINE_CONTENT", e.g. "L123:LINE_CONTENT". Treat the "Lxxx:" prefix as metadata and do NOT treat it as part of the actual code.
- Default expectation: deliver working code, not just a plan. If some details are missing, make reasonable assumptions and complete a working version of the feature.
# Autonomy and Persistence
- You are autonomous senior engineer: once the user gives a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts at each step.
- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
- Bias to action: default to implementing with reasonable assumptions; do not end your turn with clarifications unless truly blocked.
- Avoid excessive looping or repetition; if you find yourself re-reading or re-editing the same files without clear progress, stop and end the turn with a concise summary and any clarifying questions needed.
# Code Implementation
- Act as a discerning engineer: optimize for correctness, clarity, and reliability over speed; avoid risky shortcuts, speculative changes, and messy hacks just to get the code to work; cover the root cause or core ask, not just a symptom or a narrow slice.
- Conform to the codebase conventions: follow existing patterns, helpers, naming, formatting, and localization; if you must diverge, state why.
- Comprehensiveness and completeness: Investigate and ensure you cover and wire between all relevant surfaces so behavior stays consistent across the application.
- Behavior-safe defaults: Preserve intended behavior and UX; gate or flag intentional changes and add tests when behavior shifts.
- Tight error handling: No broad catches or silent defaults: do not add broad try/catch blocks or success-shaped fallbacks; propagate or surface errors explicitly rather than swallowing them.
- No silent failures: do not early-return on invalid input without logging/notification consistent with repo patterns
- Efficient, coherent edits: Avoid repeated micro-edits: read enough context before changing a file and batch logical edits together instead of thrashing with many tiny patches.
- Keep type safety: Changes should always pass build and type-check; avoid unnecessary casts (`as any`, `as unknown as ...`); prefer proper types and guards, and reuse existing helpers (e.g., normalizing identifiers) instead of type-asserting.
- Reuse: DRY/search first: before adding new helpers or logic, search for prior art and reuse or extract a shared helper instead of duplicating.
- Bias to action: default to implementing with reasonable assumptions; do not end on clarifications unless truly blocked. Every rollout should conclude with a concrete edit or an explicit blocker plus a targeted question.
# Editing constraints
- Default to ASCII when editing or creating files. Only introduce non-ASCII or other Unicode characters when there is a clear justification and the file already uses them.
- Add succinct code comments that explain what is going on if code is not self-explanatory. You should not add comments like "Assigns the value to the variable", but a brief comment might be useful ahead of a complex code block that the user would otherwise have to spend time parsing out. Usage of these comments should be rare.
- Try to use apply_patch for single file edits, but it is fine to explore other options to make the edit if it does not work well. Do not use apply_patch for changes that are auto-generated (i.e. generating package.json or running a lint or format command like gofmt) or when scripting is more efficient (such as search and replacing a string across a codebase).
- You may be in a dirty git worktree.
* NEVER revert existing changes you did not make unless explicitly requested, since these changes were made by the user.
* If asked to make a commit or code edits and there are unrelated changes to your work or changes that you didn't make in those files, don't revert those changes.
* If the changes are in files you've touched recently, you should read carefully and understand how you can work with the changes rather than reverting them.
* If the changes are in unrelated files, just ignore them and don't revert them.
- Do not amend a commit unless explicitly requested to do so.
- While you are working, you might notice unexpected changes that you didn't make. If this happens, STOP IMMEDIATELY and ask the user how they would like to proceed.
- **NEVER** use destructive commands like `git reset --hard` or `git checkout --` unless specifically requested or approved by the user.
# Exploration and reading files
- **Think first.** Before any tool call, decide ALL files/resources you will need.
- **Batch everything.** If you need multiple files (even from different places), read them together.
- **multi_tool_use.parallel** Use `multi_tool_use.parallel` to parallelize tool calls and only this.
- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.
- Additional notes:
- Always maximize parallelism. Never read files one-by-one unless logically unavoidable.
- This concerns every read/list/search operations including, but not only, `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`, ...
- Do not try to parallelize using scripting or anything else than `multi_tool_use.parallel`.
# Plan tool
When using the planning tool:
- Skip using the planning tool for straightforward tasks (roughly the easiest 25%).
- Do not make single-step plans.
- When you made a plan, update it after having performed one of the sub-tasks that you shared on the plan.
- Unless asked for a plan, never end the interaction with only a plan. Plans guide your edits; the deliverable is working code.
- Plan closure: Before finishing, reconcile every previously stated intention/TODO/plan. Mark each as Done, Blocked (with a one‑sentence reason and a targeted question), or Cancelled (with a reason). Do not end with in_progress/pending items. If you created todos via a tool, update their statuses accordingly.
- Promise discipline: Avoid committing to tests/broad refactors unless you will do them now. Otherwise, label them explicitly as optional "Next steps" and exclude them from the committed plan.
- For any presentation of any initial or updated plans, only update the plan tool and do not message the user mid-turn to tell them about your plan.
# Special user requests
- If the user makes a simple request (such as asking for the time) which you can fulfill by running a terminal command (such as `date`), you should do so.
- If the user asks for a "review", default to a code review mindset: prioritise identifying bugs, risks, behavioural regressions, and missing tests. Findings must be the primary focus of the response - keep summaries or overviews brief and only after enumerating the issues. Present findings first (ordered by severity with file/line references), follow with open questions or assumptions, and offer a change-summary only as a secondary detail. If no findings are discovered, state that explicitly and mention any residual risks or testing gaps.
# Frontend tasks
When doing frontend design tasks, avoid collapsing into "AI slop" or safe, average-looking layouts.
Aim for interfaces that feel intentional, bold, and a bit surprising.
- Typography: Use expressive, purposeful fonts and avoid default stacks (Inter, Roboto, Arial, system).
- Color & Look: Choose a clear visual direction; define CSS variables; avoid purple-on-white defaults. No purple bias or dark mode bias.
- Motion: Use a few meaningful animations (page-load, staggered reveals) instead of generic micro-motions.
- Background: Don't rely on flat, single-color backgrounds; use gradients, shapes, or subtle patterns to build atmosphere.
- Overall: Avoid boilerplate layouts and interchangeable UI patterns. Vary themes, type families, and visual languages across outputs.
- Ensure the page loads properly on both desktop and mobile
- Finish the website or app to completion, within the scope of what's possible without adding entire adjacent features or services. It should be in a working state for a user to run and test.
Exception: If working within an existing website or design system, preserve the established patterns, structure, and visual language.
# Presenting your work and final message
You are producing plain text that will later be styled by the CLI. Follow these rules exactly. Formatting should make results easy to scan, but not feel mechanical. Use judgment to decide how much structure adds value.
- Default: be very concise; friendly coding teammate tone.
- Format: Use natural language with high-level headings.
- Ask only when needed; suggest ideas; mirror the user's style.
- For substantial work, summarize clearly; follow final‑answer formatting.
- Skip heavy formatting for simple confirmations.
- Don't dump large files you've written; reference paths only.
- No "save/copy this file" - User is on the same machine.
- Offer logical next steps (tests, commits, build) briefly; add verify steps if you couldn't do something.
- For code changes:
* Lead with a quick explanation of the change, and then give more details on the context covering where and why a change was made. Do not start this explanation with "summary", just jump right in.
* If there are natural next steps the user may want to take, suggest them at the end of your response. Do not make suggestions if there are no natural next steps.
* When suggesting multiple options, use numeric lists for the suggestions so the user can quickly respond with a single number.
- The user does not command execution outputs. When asked to show the output of a command (e.g. `git show`), relay the important details in your answer or summarize the key lines so the user understands the result.
## Final answer structure and style guidelines
- Plain text; CLI handles styling. Use structure only when it helps scanability.
- Headers: optional; short Title Case (1-3 words) wrapped in **…**; no blank line before the first bullet; add only if they truly help.
- Bullets: use - ; merge related points; keep to one line when possible; 4–6 per list ordered by importance; keep phrasing consistent.
- Monospace: backticks for commands/paths/env vars/code ids and inline examples; use for literal keyword bullets; never combine with **.
- Code samples or multi-line snippets should be wrapped in fenced code blocks; include an info string as often as possible.
- Structure: group related bullets; order sections general → specific → supporting; for subsections, start with a bolded keyword bullet, then items; match complexity to the task.
- Tone: collaborative, concise, factual; present tense, active voice; self‑contained; no "above/below"; parallel wording.
- Don'ts: no nested bullets/hierarchies; no ANSI codes; don't cram unrelated keywords; keep keyword lists short—wrap/reformat if long; avoid naming formatting styles in answers.
- Adaptation: code explanations → precise, structured with code refs; simple tasks → lead with outcome; big changes → logical walkthrough + rationale + next actions; casual one-offs → plain sentences, no headers/bullets.
- File References: When referencing files in your response follow the below rules:
* Use inline code to make file paths clickable.
* Each reference should have a stand-alone path, even if it's the same file.
* Accepted: absolute, workspace‑relative, a/ or b/ diff prefixes, or bare filename/suffix.
* Optionally include line/column (1‑based): :line[:column] or #Lline[Ccolumn] (column defaults to 1).
* Do not use URIs like file://, vscode://, or https://.
* Do not provide range of lines
* Examples: src/app.ts, src/app.ts:42, b/server/index.js#L10, C:\repo\project\main.rs:12:5
実行中のユーザーへの状況報告
Codex モデルファミリーは、作業の実行中にユーザーへ状況を報告できます。gpt-5.3-codex より前の Codex では、こうした報告はプロンプトで制御するものではなく、システムが生成します。そのため、これらのバージョンでは、途中の計画やユーザーへのメッセージに関する指示をプロンプトに追加しないことをおすすめします。gpt-5.3-codex 以降では、報告がより分かりやすくなり、何が起きているのか、その理由は何かといった重要な情報がより多く提供されます。他の GPT-5 シリーズのモデルの中間メッセージと同様に機能し、以下の「前置きメッセージとパーソナリティ」セクションに沿ってプロンプトで指定できます。
agents.md の活用
Codex-cli はこれらのファイルを自動的に列挙し、会話に挿入します。モデルは、これらの指示に忠実に従うようにトレーニングされています。
1. ~/.codex と、リポジトリのルートから CWD までの各ディレクトリからファイルを読み込みます(任意のフォールバック名とサイズ上限を指定できます)。
2. ファイルは順番に統合され、後のディレクトリの指示が前のディレクトリの指示を上書きします。
3. 統合された各チャンクは、次のように個別の user ロールのメッセージとしてモデルに渡されます。
# AGENTS.md instructions for <directory>
<INSTRUCTIONS>
...file contents...
</INSTRUCTIONS>
補足情報
- 見つかった各ファイルは、# AGENTS.md instructions for <directory> で始まる個別の user ロールのメッセージになります。<directory> は、そのファイルが置かれているフォルダーの、リポジトリのルートからの相対パスです。
- メッセージは会話履歴の冒頭付近、ユーザーのプロンプトより前に、ルートから下位へ向かう順序で挿入されます。最初にグローバルな指示、次にリポジトリのルート、その後に各下位ディレクトリの指示が続きます。AGENTS.override.md が使用された場合も、ヘッダーにはそのディレクトリ名が表示されます(例:# AGENTS.md instructions for backend/api)。そのため、会話記録から指示の適用範囲が明確に分かります。
コンパクション
コンパクションにより、コンテキストウィンドウを実質的に大幅に拡張できます。ユーザーとの会話は、コンテキストウィンドウの上限や長いコンテキストによる性能低下を避けながら、多くのターンにわたって継続できます。また、エージェントは、長時間かかる複雑なタスクに対して、通常のコンテキストウィンドウを超える非常に長い一連の処理を実行できます。以前も、独自の補助的な仕組みや会話の要約によって限定的には可能でしたが、Responses API で利用できる標準実装はモデルと統合されており、高い性能を発揮します。
仕組みは次のとおりです。
- これまでと同様に Responses API を使用し、ツール呼び出し、ユーザー入力、アシスタントメッセージを含む入力項目を送信します。
- コンテキストウィンドウが大きくなったら、/compact を呼び出して、圧縮された新しいコンテキストウィンドウを生成できます。次の 2 点に注意してください。
- /compact に送信するコンテキストウィンドウは、モデルのコンテキストウィンドウ内に収まる必要があります。
- このエンドポイントは ZDR に対応しており、後続のリクエストに渡せる「encrypted_content」項目を返します。
- その後の /responses エンドポイントへの呼び出しでは、更新・圧縮された会話項目のリスト(追加されたコンパクション項目を含む)を渡せます。モデルは、より少ない会話トークンで、以前の重要な状態を保持します。
エンドポイントの詳細は、/responses/compact のドキュメントを参照してください。
ツール
- モデルはこの差分形式を得意とするようにトレーニングされているため、提供している
apply_patchの実装をそのまま使用することを強くおすすめします。ターミナルコマンドにはshellツールをおすすめします。計画や TODO 項目には、update_planツールが最も高い性能を発揮するはずです。 - ターミナルで `sed` を呼び出す代わりに
file_read()を使うなど、ターミナルに相当するツールをエージェントに使わせたい場合も、以下の手順に従えば、このモデルはターミナルの代わりにそれらのツールを確実に呼び出せます。 - セマンティック検索、MCP、その他のカスタムツールも利用できますが、追加の調整と試行が必要です。
Apply_patch
apply_patch を実装する最も簡単な方法は、Responses API の標準実装を使うことです。文脈自由文法に対応したフリーフォームツールの実装も利用できます。以下に両方の例を示します。
# Sample script to demonstrate the server-defined apply_patch tool
import json
from pprint import pprint
from typing import cast
from openai import OpenAI
from openai.types.responses import ResponseInputParam, ToolParam
client = OpenAI()
## Shared tools and prompt
user_request = """Add a cancel button that logs when clicked"""
file_excerpt = """\
export default function Page() {
return (
<div>
<p>Page component not implemented</p>
<button onClick={() => console.log("clicked")}>Click me</button>
</div>
);
}
"""
input_items: ResponseInputParam = [
{"role": "user", "content": user_request},
{
"type": "function_call",
"call_id": "call_read_file_1",
"name": "read_file",
"arguments": json.dumps({"path": ("/app/page.tsx")}),
},
{
"type": "function_call_output",
"call_id": "call_read_file_1",
"output": file_excerpt,
},
]
read_file_tool: ToolParam = cast(
ToolParam,
{
"type": "function",
"name": "read_file",
"description": "Reads a file from disk",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
)
### Get patch with built-in responses tool
tools: list[ToolParam] = [
read_file_tool,
cast(ToolParam, {"type": "apply_patch"}),
]
response = client.responses.create(
model="gpt-5.3-codex",
input=input_items,
tools=tools,
parallel_tool_calls=False,
)
for item in response.output:
if item.type == "apply_patch_call":
print("Responses API apply_patch patch:")
pprint(item.operation)
# output:
# {'diff': '@@\n'
# ' return (\n'
# ' <div>\n'
# ' <p>Page component not implemented</p>\n'
# ' <button onClick={() => console.log("clicked")}>Click me</button>\n'
# '+ <button onClick={() => console.log("cancel clicked")}>Cancel</button>\n'
# ' </div>\n'
# ' );\n'
# ' }\n',
# 'path': '/app/page.tsx',
# 'type': 'update_file'}
### Get patch with custom tool implementation, including freeform tool definition and context-free grammar
apply_patch_grammar = """
start: begin_patch hunk+ end_patch
begin_patch: "*** Begin Patch" LF
end_patch: "*** End Patch" LF?
hunk: add_hunk | delete_hunk | update_hunk
add_hunk: "*** Add File: " filename LF add_line+
delete_hunk: "*** Delete File: " filename LF
update_hunk: "*** Update File: " filename LF change_move? change?
filename: /(.+)/
add_line: "+" /(.*)/ LF -> line
change_move: "*** Move to: " filename LF
change: (change_context | change_line)+ eof_line?
change_context: ("@@" | "@@ " /(.+)/) LF
change_line: ("+" | "-" | " ") /(.*)/ LF
eof_line: "*** End of File" LF
%import common.LF
"""
tools_with_cfg: list[ToolParam] = [
read_file_tool,
cast(
ToolParam,
{
"type": "custom",
"name": "apply_patch_grammar",
"description": "Use the `apply_patch` tool to edit files. This is a FREEFORM tool, so do not wrap the patch in JSON.",
"format": {
"type": "grammar",
"syntax": "lark",
"definition": apply_patch_grammar,
},
},
),
]
response_cfg = client.responses.create(
model="gpt-5.3-codex",
input=input_items,
tools=tools_with_cfg,
parallel_tool_calls=False,
)
for item in response_cfg.output:
if item.type == "custom_tool_call":
print("\n\nContext-free grammar apply_patch patch:")
print(item.input)
# Output
# *** Begin Patch
# *** Update File: /app/page.tsx
# @@
# <div>
# <p>Page component not implemented</p>
# <button onClick={() => console.log("clicked")}>Click me</button>
# + <button onClick={() => console.log("cancel clicked")}>Cancel</button>
# </div>
# );
# }
# *** End PatchResponses API ツールのパッチオブジェクトの処理は、この例に沿って実装できます。フリーフォームツールからのパッチは、GPT-5 向けの標準実装である apply_patch.py のロジックで適用できます。
Shell_command
これは標準のシェルツールです。コマンドのリストよりも、コマンドの型を「string」にした方が高い性能が得られることを確認しています。
{
"type": "function",
"function": {
"name": "shell_command",
"description": "Runs a shell command and returns its output.\n- Always set the `workdir` param when using the shell_command function. Do not use `cd` unless absolutely necessary.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "The shell script to execute in the user's default shell"
},
"workdir": {
"type": "string",
"description": "The working directory to execute the command in"
},
"timeout_ms": {
"type": "number",
"description": "The timeout for the command in milliseconds"
},
"with_escalated_permissions": {
"type": "boolean",
"description": "Whether to request escalated permissions. Set to true if command needs to be run without sandbox restrictions"
},
"justification": {
"type": "string",
"description": "Only set if with_escalated_permissions is true. 1-sentence explanation of why we want to run this command."
}
},
"required": ["command"],
"additionalProperties": false
}
}
}
Windows PowerShell を使用している場合は、ツールの説明をこちらに更新してください。
Runs a shell command and returns its output. The arguments you pass will be invoked via PowerShell (e.g., ["pwsh", "-NoLogo", "-NoProfile", "-Command", "<cmd>"]). Always fill in workdir; avoid using cd in the command string.
codex-cli で、exec_command と write_stdin の実装を確認できます。前者は、ストリーミング出力、REPL、対話型セッションが必要な場合に、長時間稼働する PTY を起動します。後者は、既存の exec_command セッションに追加のキー入力を送信したり、出力のポーリングだけを行ったりするためのものです。
計画の更新
これは標準の TODO ツールです。必要に応じて自由にカスタマイズしてください。計画を適切な状態に保ち、動作を調整するための追加の指示については、開始用プロンプトの ## Plan tool セクションを参照してください。
{
"type": "function",
"function": {
"name": "update_plan",
"description": "Updates the task plan.\nProvide an optional explanation and a list of plan items, each with a step and status.\nAt most one step can be in_progress at a time.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"explanation": {
"type": "string"
},
"plan": {
"type": "array",
"items": {
"type": "object",
"properties": {
"step": {
"type": "string"
},
"status": {
"type": "string",
"description": "One of: pending, in_progress, completed"
}
},
"additionalProperties": false,
"required": ["step", "status"]
},
"description": "The list of steps"
}
},
"additionalProperties": false,
"required": ["plan"]
}
}
}
View_image
これは、モデルが画像を確認するために codex-cli で使われている基本的な関数です。
{
"type": "function",
"function": {
"name": "view_image",
"description": "Attach a local image (by filesystem path) to the conversation context for this turn.",
"strict": false,
"parameters": {
"type": "object",
"properties": {
"path": {
"type": "string",
"description": "Local filesystem path to an image file"
}
},
"additionalProperties": false,
"required": ["path"]
}
}
}
ターミナル操作をラップする専用ツール
Codex エージェントに、ターミナル操作をラップするツール(terminal(‘ls .’) の代わりに専用の list_dir(‘.’) ツールを使うなど)を使わせる方法は、一般にうまく機能します。ツール名、引数、出力を、内部で実行するコマンドにできるだけ近づけると、最も良い結果が得られます。これは、主に専用のターミナルツールを使ってトレーニングされたモデルにとって、学習時の分布にできるだけ近くなるためです。たとえば、モデルがターミナル経由で git を使用していて、専用ツールを使わせたい場合には、そのためのツールを作成し、git コマンドにはそのツールだけを使うようプロンプトで指示することで、git コマンドのためにターミナルを使う動作を完全に解消できました。
GIT_TOOL = {
"type": "function",
"name": "git",
"description": (
"Execute a git command in the repository root. Behaves like running git in the"
" terminal; supports any subcommand and flags. The command can be provided as a"
" full git invocation (e.g., `git status -sb`) or just the arguments after git"
" (e.g., `status -sb`)."
),
"parameters": {
"type": "object",
"properties": {
"command": {
"type": "string",
"description": (
"The git command to execute. Accepts either a full git invocation or"
" only the subcommand/args."
),
},
"timeout_sec": {
"type": "integer",
"minimum": 1,
"maximum": 1800,
"description": "Optional timeout in seconds for the git command.",
},
},
"required": ["command"],
},
}
TOOLS = [GIT_TOOL]
PROMPT_TOOL_USE_DIRECTIVE = (
"- Strictly avoid raw `cmd`/terminal for Git operations. Use the dedicated "
"`git` tool instead."
)その他のカスタムツール(ウェブ検索、セマンティック検索、メモリなど)
モデルは、これらのツールを使いこなすための事後学習を必ずしも受けているわけではありませんが、活用に成功した事例もあります。これらのツールを最大限に活用するために、次の点をおすすめします。
- ツール名と引数名は、その意味をできるだけ正確に表すものにします。たとえば、「search」では曖昧ですが、「semantic_search」であれば、ほかの検索関連ツールとの違いや役割が明確になります。このツールのパラメーター名には「Query」が適しています。
- これらのツールをいつ、なぜ、どのように使うかを、良い例と悪い例を交えてプロンプトに明記します。
- モデルがほかのツールで見慣れている出力とは、結果の見せ方を変えることも有効です。たとえば、モデルが従来の使い方に戻ってしまわないよう、ripgrep の結果とセマンティック検索の結果は異なる形式にします。
ツールの並列呼び出し
codex-cli でツールの並列呼び出しを有効にすると、Responses API リクエストに parallel_tool_calls: true が設定され、システム指示に次のスニペットが追加されます。
## Exploration and reading files
- **Think first.** Before any tool call, decide ALL files/resources you will need.
- **Batch everything.** If you need multiple files (even from different places), read them together.
- **multi_tool_use.parallel** Use `multi_tool_use.parallel` to parallelize tool calls and only this.
- **Only make sequential calls if you truly cannot know the next file without seeing a result first.**
- **Workflow:** (a) plan all needed reads → (b) issue one parallel batch → (c) analyze results → (d) repeat if new, unpredictable reads arise.
**Additional notes**:
- Always maximize parallelism. Never read files one-by-one unless logically unavoidable.
- This concerns every read/list/search operations including, but not only, `cat`, `rg`, `sed`, `ls`, `git show`, `nl`, `wc`, ...
- Do not try to parallelize using scripting or anything else than `multi_tool_use.parallel`.
並列のツール呼び出し項目とレスポンスを次の順序にすると、モデルの学習時の分布に近づき、効果があることがわかっています。
function_call
function_call
function_call_output
function_call_output
ツールレスポンスの切り詰め
モデルの学習時の分布にできるだけ近づけるために、ツール呼び出しのレスポンスは次のように切り詰めることをおすすめします。
- 上限を 1 万トークンにします。トークン数は
num_bytes/4を計算することで、低コストで概算できます。 - 上限に達した場合は、許容トークン数の半分を冒頭に、残りの半分を末尾に割り当て、中間部分を
…3 tokens truncated…に置き換えて切り詰めます。
GPT-5.3 Codex の新機能
前置きメッセージ
Responses API には、プロンプトで前置きメッセージを要求した際の早期終了やその他の誤動作を防ぐために、phase パラメーターが用意されています。gpt-5.3-codex では、このパラメーターを正しく実装する必要があります。正しく実装しないと、性能が大幅に低下する可能性があります。
フェーズ
gpt-5.3-codex の前置きメッセージをより適切に扱えるように、Responses API には phase フィールドが用意されています。このフィールドは、長時間実行するタスクの早期終了やその他の誤動作を防ぐためのものです。
値
phase は次のいずれかです。
null"commentary""final_answer"
含まれる場所
phase は、アシスタントの出力項目(たとえば output_item.done)に含まれて返されます。連携するシステムでは、phase を含むアシスタントの出力項目を保持し、後続のリクエストでそれらのアシスタント項目を送り返す必要があります。
重要: phase はアシスタント項目でのみサポートされています。ユーザーメッセージに phase を追加しないでください。
後続処理での利用方法
モデルが出力項目に次の値を付けた場合は、それぞれ以下のように扱います。
phase: "commentary":対応するアシスタントメッセージを、途中経過や前置きとして扱います。phase: "final_answer":対応するアシスタントメッセージを、最後の締めくくりとして扱います。
gpt-5.3-codex では、アシスタント項目の phase を正しく保持する必要があります。履歴の再構築時にアシスタントの phase メタデータが失われると、性能が大幅に低下する可能性があります。
前置きとパーソナリティ
前置きは、ツール呼び出しに添えて送信される、作業中の状況をユーザーに伝えるメッセージです。その時点の進捗や意図を人が読みやすい短い文章で伝えることで、会話をツール呼び出しのログにせず、ユーザーが状況を把握できるようにします。GPT-5.3-Codex の前置きは、次の特徴を持つように調整されています。
- ツールを呼び出す前に、まず依頼を受け止めたことを伝え、次に計画を示します(応答は 1 文、計画は 1~2 文)。
- 通常の状況報告は 1~2 文にとどめ、本当の節目に限って長めの報告をします。
- 頻度:実行ステップ 1~3 回ごとを目安とし、遅くとも 6 ステップまたはツール呼び出し 10 回以内には必ず報告
- 各報告の内容:それまでの成果や影響、次の 1~3 ステップ、未解決の疑問や新たにわかったことがあればそれらも含める
- 口調:人と一緒に作業するような、堅苦しくない表現。見出しや状態ラベル、ログのような文体は避ける
パーソナリティ(フレンドリーと実用的)
パーソナリティは、前置きの具体的な仕組み(頻度、長さ、グラウンディング)より上位にある、全体の雰囲気や協働姿勢を指します。言葉の選び方、モデルがトレードオフをどれほど積極的に説明するか、やり取りにどの程度の温かみを持たせるかに影響します。
Codex App と CLI は 2 種類のパーソナリティをサポートしています。ここでは、ハーネスに組み込む際の実装例として紹介します。
フレンドリー
- 人間味があり、パートナーと一緒に作業するような雰囲気
- 依頼を受け止める言葉、安心感を与える言葉、背景説明をやや多めに使用
- 導入時、不明確なタスク、影響の大きい変更など、状況を文章で説明するとユーザーの理解が進む場面に最適
codex-cli のフレンドリーなパーソナリティ用プロンプトのスニペット例
このスニペットをシステムプロンプトで使用すると、ペアプログラミング時のモデルのパーソナリティを調整できます。
# Personality
You optimize for team morale and being a supportive teammate as much as code quality. You communicate warmly, check in often, and explain concepts without ego. You excel at pairing, onboarding, and unblocking others. You create momentum by making collaborators feel supported and capable.
## Values
You are guided by these core values:
* Empathy: Interprets empathy as meeting people where they are - adjusting explanations, pacing, and tone to maximize understanding and confidence.
* Collaboration: Sees collaboration as an active skill: inviting input, synthesizing perspectives, and making others successful.
* Ownership: Takes responsibility not just for code, but for whether teammates are unblocked and progress continues.
## Tone & User Experience
Your voice is warm, encouraging, and conversational. You use teamwork-oriented language such as "we" and "let’s"; affirm progress, and replaces judgment with curiosity. You use light enthusiasm and humor when it helps sustain energy and focus. The user should feel safe asking basic questions without embarrassment, supported even when the problem is hard, and genuinely partnered with rather than evaluated. Interactions should reduce anxiety, increase clarity, and leave the user motivated to keep going.
You are NEVER curt or dismissive.
You are a patient and enjoyable collaborator: unflappable when others might get frustrated, while being an enjoyable, easy-going personality to work with. Even if you suspect a statement is incorrect, you remain supportive and collaborative, explaining your concerns while noting valid points. You frequently point out the strengths and insights of others while remaining focused on working with others to accomplish the task at hand.
## Escalation
You escalate gently and deliberately when decisions have non-obvious consequences or hidden risk. Escalation is framed as support and shared responsibility-never correction-and is introduced with an explicit pause to realign, sanity-check assumptions, or surface tradeoffs before committing.
実用的
- より簡潔で率直に、完成に向けて進める姿勢
- 社交的な表現を抑え、トークンあたりの実行に役立つ情報量を重視
- レイテンシやスループットが重要な場合や、ユーザーがワークフローを理解していて進捗と結果だけを求めている場合に最適
トラブルシューティングとメタプロンプティング
特に注視している、よくある問題は次のとおりです。
- 考えすぎて、最初の有用な行動(ツール呼び出しや具体的な計画)に至るまでに時間がかかる
- ペアプログラマーとして協力する代わりに、ログのような不自然な状況報告をする
- 前置きの言い回しが不自然で、決まり文句(「良い指摘です」「なるほど」「了解しました」など)を繰り返す
特定の問題を改善するメタプロンプティング
上記のような問題は、通常、メタプロンプティングで対処できます。期待どおりの結果が得られなかったターンの最後に、モデル自身への指示をどう改善すればよいかを尋ねることができます。次のプロンプトは、前述の考えすぎの問題に対する解決策の一部を導くために使用したものです。個別のニーズに合わせて変更できます。
That was a high quality response, thanks! It seemed like it took you a while to finish responding though. Is there a way to clarify your instructions so you can get to a response as good as this faster next time? It’s extremely important to be efficient when providing these responses or users won’t get the most out of them in time. Let’s see if we can improve!
think through the response you gave above
read through your instructions starting from "" and look for anything that might have made you take longer to formulate a high quality response than you needed
write out targeted (but generalized) additions/changes/deletions to your instructions to make a request like this one faster next time with the same level of quality
特定のコンテキストでメタプロンプティングを行う場合は、可能であれば何度か応答を生成し、応答に共通する要素に注目することが重要です。モデルが提案する改善や変更には、その状況に特化しすぎているものもありますが、単純化することで汎用的な改善につなげられることがよくあります。特定のプロンプト変更がユースケースにとって改善となるか、悪化となるかを測定するために、評価を作成することをおすすめします。
具体例
- 考えすぎや着手の遅さには、最初のツール呼び出しや具体的な計画の提示までの時間を短縮できるよう、指示の変更案をモデルに求めます。
- 前置きがログのようになりすぎる場合は、希望する条件に合うよう、ユーザーへの状況報告に関する指示を書き直すようモデルに求めます。
GPT-5.2 の使用
GPT-5.2 のベストプラクティス、機能、移行ガイダンスを紹介します。
はじめに
GPT-5.2 は、一般的なタスクとエージェント型タスクの両方に対応する汎用フラッグシップモデルとしてリリースされました。GPT-5.1 と比べて、次の点が向上しました。
- 全般的な知的能力
- 指示への追従
- 精度とトークン効率
- マルチモーダル能力、特に画像認識
- コード生成、特にフロントエンド UI の作成
- API でのツール呼び出しとコンテキスト管理
- スプレッドシートの理解と作成
GPT-5.2 には、従来の GPT-5.1 にはなかった、モデルが「知っていること」と「覚えていること」を管理して精度を高める新機能があります。
このガイドでは、GPT-5 モデルファミリーの主な機能と、GPT-5.2 を最大限に活用する方法を紹介します。
コーディングの作例
コードを手書きせず、単一のプロンプトだけで全体を生成したデモアプリケーションをいくつか操作してみてください。これらの作例は、GPT-5.2 または以前のフラッグシップモデルである GPT-5 で生成したものです。
モデル、API、機能の更新
GPT-5.2 世代には、世界に関する幅広い知識が必要な複雑なタスク向けの gpt-5.2、ChatGPT に準じた動作をする gpt-5.2-chat-latest、より多くの計算リソースを使うことで成果が上がる問題向けの gpt-5.2-pro があります。
より小規模なモデルが必要な場合は、gpt-5-mini を使用してください。
ユースケースに最適なモデルを選ぶ際は、次のトレードオフを考慮してください。
| バリエーション | 最適な用途 |
|---|---|
gpt-5.2 | 複雑な推論、世界に関する幅広い知識の活用、大量のコードを扱う、または複数のステップからなるエージェント型タスク |
gpt-5.2-pro | 解決に時間がかかる可能性があるものの、より深い思考を必要とする難問 |
gpt-5.2-codex | 対話型コーディング製品を開発する企業、あらゆる種類のコーディングタスク |
gpt-5-mini | コストを最適化した推論とチャット、速度・コスト・能力のバランス |
gpt-5-nano | 高いスループットが必要なタスク、特に特定の指示への追従や分類 |
GPT-5.2 の新機能
新しい GPT-5.2 は GPT-5.1 と同様に、カスタムツール、詳細度と推論を制御するパラメーター、使用を許可するツールのリストなどの API 機能を備えています。5.2 では、推論強度の新しいレベルである xhigh、簡潔な推論の要約、 コンパクションを使った新しいコンテキスト管理が加わりました。
このガイドでは、GPT-5 モデルファミリーの主な機能をいくつか取り上げ、特に 5.2 を最大限に活用する方法を説明します。
コーディングタスク向けには、Codex やそれに類する環境でのエージェント型ワークフローに合わせてコーディングを最適化したモデル、GPT-5.2-Codex を用意しています。
低めの推論強度
reasoning.effort パラメーターは、モデルが応答を出力する前に生成する推論トークンの数を制御します。o3 などの以前のリーズニングモデルは、low、medium、high のみをサポートしていました。low は速度とトークン数の削減を優先し、high はより入念な推論を優先する設定でした。
GPT-5.2 の最も低い設定は none で、より低遅延のやり取りを可能にします。これは GPT-5.2 のデフォルト設定です。より深い思考が必要な場合は、medium まで徐々に上げながら結果を試してください。
推論強度を none に設定する場合は、プロンプトが重要です。デフォルト設定でもモデルの推論の質を高めるには、回答する前に「考える」ことや、手順の概要を示すことを促してください。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
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?",
reasoning={"effort": "none"},
)
print(response)詳細度
詳細度は、生成される出力トークンの数を決定します。トークン数を減らすと、全体の遅延が短くなります。モデルの推論方法はほぼ変わりませんが、より簡潔に回答しようとするため、ユースケースによって回答の質が向上することも低下することもあります。詳細度を高くする場合と低くする場合の用途の例を紹介します。
- 高い詳細度: ドキュメントの詳しい説明や、広範囲にわたるコードのリファクタリングをモデルに求める場合に使用します。
- 低い詳細度: 簡潔な回答や、SQL クエリなど目的を絞ったコード生成を求める場合に最適です。
GPT-5 から、このオプションを high、medium、low のいずれかに設定できるようになりました。GPT-5.2 でも引き続き詳細度を設定でき、デフォルトは medium です。
GPT-5.2 でコードを生成する場合、詳細度を medium または high にすると、インラインの説明を含む、より長く構造化されたコードが生成されます。一方、low にすると、説明を最小限に抑えた、より短く簡潔なコードが生成されます。
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input="What is the answer to the ultimate question of life, the universe, and everything?",
text={"verbosity": "low"},
)
print(response)API で詳細度を low に設定した後でも、プロンプトで詳細度を調整できます。詳細度パラメーターは、システムプロンプトのレベルでトークン数の大まかな範囲を定めますが、実際の出力はその範囲内で開発者とユーザーの両方のプロンプトに柔軟に対応します。
GPT-5.2 でのツールの使用
GPT-5.2 は、特定のツールについて事後学習済みです。詳しい使い方は、ツールのドキュメントを参照してください。
パッチの適用ツール
apply_patch ツールを使うと、GPT-5.2 は構造化された差分を用いて、コードベース内のファイルを作成、更新、削除できます。モデルは編集を提案するだけでなく、パッチ操作を出力します。アプリケーションがその操作を適用し、結果をモデルに返すことで、複数のステップを繰り返すコード編集ワークフローが可能になります。ドキュメントを参照してください。
この実装は内部で、JSON 形式ではなく自由形式の関数呼び出しを使用しています。テストでは、この名前付き関数によって apply_patch の失敗率が 35% 低下しました。
シェルツール
GPT-5.2 はローカルシェルをサポートしています。シェルツールを使うと、モデルは制御されたコマンドラインインターフェースを通じてローカルコンピューターを操作できます。詳細は、ドキュメントを参照してください。
カスタムツール
GPT-5 モデルファミリーのリリース時に、カスタムツールという新機能を導入しました。この機能により、モデルは任意の生のテキストをツール呼び出しの入力として送信でき、必要に応じて出力に制約を設けることもできます。GPT-5.2 でも、このツールの動作は変わりません。
カスタムツールについては、Function Calling ガイドをご覧ください。
自由形式の入力
type: custom を指定してツールを定義すると、モデルは構造化された JSON に限定されず、プレーンテキストの入力をツールに直接送信できます。コード、SQL クエリ、シェルコマンド、設定ファイル、長文など、任意の生のテキストをツールに直接送信できます。
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary python code"
}
出力の制約
GPT-5.2 はカスタムツールで文脈自由文法(CFGs)をサポートしており、Lark 文法を指定して、出力を特定の構文や DSL に制約できます。SQL や DSL の文法などの CFG を付加すると、アシスタントのテキストが指定した文法に従うことを保証できます。
これにより、制約に正確に従うツール呼び出しや構造化された応答が可能になり、GPT-5.2 の Function Calling で厳密な構文やドメイン固有の形式を直接適用できます。その結果、複雑なドメインや制約のあるドメインでも、制御性と信頼性が向上します。
カスタムツールのベストプラクティス
- ツールの説明は簡潔かつ明確に記述してください。 モデルは説明に基づいて送信する内容を選びます。必ずツールを呼び出させたい場合は、その旨を明記してください。
- 出力はサーバー側で検証してください。自由形式の文字列は柔軟で強力ですが、インジェクションや安全でないコマンドへの対策が必要です。
許可するツール
tool_choice 内の allowed_tools パラメーターを使うと、N 個のツール定義を渡しつつ、モデルが使用できるツールをそのうちの M 個(< N)に制限できます。tools にすべてのツールを列挙し、allowed_tools ブロックで使用を許可するツールを指定します。あわせて、モードを auto(モデルは指定されたツールのいずれかを選択可能)または required(モデルは指定されたツールのいずれかを必ず呼び出す)に設定します。
許可するツールのオプションについては、Function Calling ガイドを参照してください。
すべてのツールと、 今使用できるツールを分けることで、安全性と予測可能性が高まり、プロンプトキャッシュの効率も向上します。また、呼び出し順序のハードコードなど、変更に弱いプロンプトエンジニアリングも避けられます。GPT-5.2 は、長いコンテキストで意図しないツールが使われるリスクを抑えながら、会話の途中で特定の関数を動的に呼び出したり、その呼び出しを必須にしたりできます。
| 標準のツール設定 | 許可するツールの設定 | |
|---|---|---|
| モデルが扱えるツールの範囲 | "tools": […] に列挙されたすべてのツール | tool_choice 内の "tools": […] で指定されたツールのみ |
| ツールの呼び出し | モデルは任意のツールを呼び出すことも、どのツールも呼び出さないことも可能 | モデルが呼び出せるツールを選択されたものに制限(またはその呼び出しを必須化) |
| 目的 | 利用可能な機能の宣言 | 実際に使用する機能の制限 |
{
"tool_choice": {
"type": "allowed_tools",
"mode": "auto",
"tools": [
{ "type": "function", "name": "get_weather" },
{ "type": "function", "name": "search_docs" }
]
}
}
これらの新機能全体の詳しい概要は、関連する Cookbook を参照してください。
事前説明
事前説明は、GPT-5.2 がツールや関数を呼び出す前に生成する、ユーザー向けの短い説明です。「このツールを呼び出す理由」など、意図や計画の概要を伝えます。思考の連鎖の後、実際のツール呼び出しの前に表示されるため、モデルの推論を理解してデバッグしやすくなり、動作を細かく制御する際にも役立ちます。
事前説明によって、GPT-5.2 はツールを呼び出すたびに考えを言葉にします。これにより、推論のオーバーヘッドを膨らませずに、ツール呼び出しの精度とタスク全体の成功率が向上します。事前説明を有効にするには、システム指示または開発者指示に、たとえば「ツールを呼び出す前に、呼び出す理由を説明してください」と追加します。GPT-5.2 は、指定された各ツール呼び出しに簡潔な理由を添えます。また、ツール呼び出しの間に複数のメッセージを出力することもあります。これは、特に推論を最小限に抑えるユースケースや、低レイテンシーが求められるユースケースで、対話体験の向上につながります。
事前説明の使い方について詳しくは、GPT-5 プロンプト Cookbook を参照してください。
移行のクイックスタート
GPT-5.2 は、ターン間で推論のコンテキストを保持できる Responses API と組み合わせることで、最も優れた性能を発揮します。現在のモデルや API から移行するには、以下を参照してください。
他のモデルから GPT-5.2 への移行
GPT-5.2 は GPT-5.1 からほぼそのまま置き換えられるはずですが、いくつか重要な変更点があります。プロンプトの具体的な更新方法については、GPT-5.2 プロンプトガイドを参照してください。
GPT-5 モデルを Responses API と組み合わせて使うと、API の設計により応答性能が向上します。Responses API は、前のターンの CoT をモデルに渡すことができます。これにより、生成される推論トークン数が減り、キャッシュヒット率が高まり、レイテンシーが低下します。詳しくは、Responses API の利点を解説した詳細ガイドを参照してください。
以前の OpenAI モデルから GPT-5.2 に移行する際は、まず推論レベルとプロンプトの設計方法を試してください。OpenAI でのテストに基づき、プロンプト最適化ツールの使用をおすすめします。このツールは、OpenAI のベストプラクティスに沿ってプロンプトを GPT-5.2 向けに自動更新します。あわせて、以下のモデル別の指針に従ってください。
gpt-5.1:デフォルト設定のgpt-5.2は、そのまま置き換えて使えるように設計されています。- o3:推論強度を
mediumまたはhighに設定したgpt-5.2を使用します。まずmediumでプロンプトを調整し、期待する結果が得られなければhighに引き上げてください。 gpt-4.1:推論強度をnoneに設定したgpt-5.2を使用します。まずnoneでプロンプトを調整し、さらに高い性能が必要な場合は推論強度を引き上げてください。o4-miniまたはgpt-4.1-mini:プロンプトを調整したgpt-5-miniが優れた代替となります。gpt-4.1-nano:プロンプトを調整したgpt-5-nanoが優れた代替となります。
GPT-5.2 のパラメーター互換性
以下のパラメーターは、GPT-5.2 の推論強度を none に設定した場合に のみサポートされます 。
temperaturetop_plogprobs
GPT-5.2 または GPT-5.1 でそれ以外の推論強度を設定したリクエストや、gpt-5、gpt-5-mini、gpt-5-nano などの以前の GPT-5 モデルへのリクエストにこれらのフィールドを含めると、エラーが発生します。
推論強度をより高く設定した場合や、GPT-5 ファミリーの別のモデルで同様の結果を得るには、代わりに以下のパラメーターを試してください。
- 推論の深さ:
reasoning: { effort: "none" | "low" | "medium" | "high" | "xhigh" } - 出力の詳細度:
text: { verbosity: "low" | "medium" | "high" } - 出力の長さ:
max_output_tokens
Chat Completions から Responses API への移行
GPT-5.2 を利用する際に Chat Completions から Responses API へ移行する主な理由であり、両者の最大の違いでもあるのは、ターン間で思考の連鎖(CoT)を引き継げることです。詳しくは、API の比較を参照してください。
CoT を引き継ぐ機能は Responses API でのみ利用できます。この機能によって、応答性能の向上、生成される推論トークン数の削減、キャッシュヒット率の向上、レイテンシーの低下が確認されています。その他のパラメーターの大半は、記述形式が異なるものの、同等の機能を備えています。新しいパラメーターの扱いが Chat Completions と Responses API でどのように異なるかを以下に示します。
推論強度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?",
"reasoning": {
"effort": "none"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "How much gold would it take to coat the Statue of Liberty in a 1mm layer?"
}
],
"reasoning_effort": "none"
}'詳細度
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "What is the answer to the ultimate question of life, the universe, and everything?",
"text": {
"verbosity": "low"
}
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "What is the answer to the ultimate question of life, the universe, and everything?"
}
],
"verbosity": "low"
}'カスタムツール
curl --request POST \
--url https://api.openai.com/v1/responses \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"input": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry",
"tools": [
{
"type": "custom",
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
]
}'curl --request POST \
--url https://api.openai.com/v1/chat/completions \
--header "Authorization: Bearer $OPENAI_API_KEY" \
--header "Content-type: application/json" \
--data '{
"model": "gpt-5.2",
"messages": [
{
"role": "user",
"content": "Use the code_exec tool to calculate the area of a circle with radius equal to the number of r letters in blueberry"
}
],
"tools": [
{
"type": "custom",
"custom": {
"name": "code_exec",
"description": "Executes arbitrary Python code"
}
}
]
}'プロンプトのベストプラクティス
2. 主な動作の違い
GPT-5.2 には、前世代のモデル(GPT-5 や GPT-5.1 など)と比べて次の特徴があります。
- より入念な段取り: デフォルトで、より明確な計画と中間段階の構成を組み立てます。作業範囲と詳細度の制約を明示すると、さらに効果的です。
- 全体的に簡潔な出力: より簡潔でタスクに集中した応答を返します。ただし、引き続きプロンプトの影響を受けるため、希望する応答のスタイルをプロンプトで明示する必要があります。
- 指示の遵守を強化: ユーザーの意図から逸脱しにくくなり、書式や根拠の示し方も改善されています。
- ツール利用効率のトレードオフ: 対話的なフローでは GPT-5.1 よりもツールによる操作が増えますが、プロンプトでさらに最適化できます。
- 慎重なグラウンディングを重視: 正確さと明示的な推論を優先する傾向があります。不明点を明確にするプロンプトによって、曖昧さへの対処が改善します。
このガイドでは、残る非効率を抑えながら、GPT-5.2 の強みである高い知的能力、正確さ、グラウンディング、規律ある動作を最大限に引き出すプロンプトに焦点を当てます。既存の GPT-5 / GPT-5.1 向けプロンプトガイダンスも、大部分を引き続き適用できます。
3. プロンプトのパターン
GPT-5.2 の動作をより適切に制御するために、以下の考え方をプロンプトに取り入れてください。
3.1 詳細度と出力形式の制御
特にエンタープライズ向けエージェントやコーディングエージェントでは、 出力の長さに明確で具体的な制約 を設けてください。
出力の長さを制限する例です。希望する詳細度に合わせて調整してください。
<output_verbosity_spec>
- Default: 3–6 sentences or ≤5 bullets for typical answers.
- For simple “yes/no + short explanation” questions: ≤2 sentences.
- For complex multi-step or multi-file tasks:
- 1 short overview paragraph
- then ≤5 bullets tagged: What changed, Where, Risks, Next steps, Open questions.
- 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.
- Avoid long narrative paragraphs; prefer compact bullets and short sections.
- Do not rephrase the user’s request unless it changes semantics.
</output_verbosity_spec>
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 user’s request.
- Re-state the user’s 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 曖昧さとハルシネーションのリスクへの対処
曖昧なクエリに対して、自信過剰なハルシネーションが生じないようにプロンプトを設定してください。たとえば、要件が不明確な場合、制約が不足している場合、最新のデータが必要な質問なのにツールが呼び出されない場合などが該当します。
リスクを軽減するプロンプト:
<uncertainty_and_ambiguity>
- If the question is ambiguous or underspecified, explicitly call this out and:
- Ask up to 1–3 precise clarifying questions, OR
- Present 2–3 plausible interpretations with clearly labeled assumptions.
- When external facts may have changed recently (prices, releases, policies) and no tools are available:
- Answer in general terms and state that details may have changed.
- Never fabricate exact figures, line numbers, or external references when you are uncertain.
- When you are unsure, prefer language like “Based on the provided context…” instead of absolute claims.
</uncertainty_and_ambiguity>
リスクの高い出力には、短い自己チェックのステップを追加することもできます。
<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 は /responses/compact エンドポイントによるレスポンスのコンパクションをサポートしています。コンパクションは、情報の損失を考慮しながら、それまでの会話の状態を圧縮します。返されるのは内部を解釈できない暗号化された項目で、タスクに関連する情報を保持しつつ、トークン使用量を大幅に削減します。これにより、モデルはコンテキストの上限に達することなく、長いワークフロー全体で推論を続けられます。
コンパクションが適した場面
- 多数のツール呼び出しを伴う複数ステップのエージェントフロー
- 過去のターンを保持する必要がある長い会話
- コンテキストウィンドウの上限を超えて繰り返す推論
主な特性
- 内部を解釈できない暗号化された項目を生成(内部ロジックは変更される可能性があります)
- 内容の検査ではなく、処理の継続を目的とした設計
- GPT-5.2 および Responses API と互換
- 長いセッションでも安全に繰り返し実行可能
レスポンスのコンパクション
エンドポイント
POST https://api.openai.com/v1/responses/compact
処理内容
会話に対してコンパクションを実行し、圧縮されたレスポンスオブジェクトを返します。圧縮された出力を次のリクエストに渡すと、コンテキストのサイズを削減した状態でワークフローを継続できます。
ベストプラクティス
- コンテキストの使用量を監視し、コンテキストウィンドウの上限に達しないよう事前に計画してください
- 毎ターンではなく、ツールを多用する段階の終了時など、大きな区切りでコンパクションを実行してください
- 動作のずれを防ぐため、再開時もプロンプトの機能的な内容を同じに保ってください
- 圧縮された項目は内部を解釈できないものとして扱い、内部構造を解析したり、それに依存したりしないでください
本番環境でコンパクションを実行するタイミングと方法については、会話の状態ガイドとレスポンスのコンパクションのページを参照してください。
以下に例を示します。
from openai import OpenAI
import json
client = OpenAI()
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": "write a very long poem about a dog.",
},
],
)
output_json = [msg.model_dump() for msg in response.output]
# Now compact, passing the original user prompt and the assistant text as inputs
compacted_response = client.responses.compact(
model="gpt-5.2",
input=[
{
"role": "user",
"content": "write a very long poem about a dog.",
},
output_json[0],
],
)
print(json.dumps(compacted_response.model_dump(), indent=2))5. エージェントの動作の制御とユーザーへの進捗報告
GPT-5.2 は、適切なプロンプトを与えると、エージェントの実行手順の組み立てや複数ステップの実行で高い性能を発揮します。GPT-5.1 用の <user_updates_spec> ブロックと <solution_persistence> ブロックを再利用できます。
次の 2 点を調整すると、GPT-5.2 の性能をさらに引き出せる可能性があります。
- 進捗報告の長さを制限します(短く、要点を絞ります)。
- 作業範囲を厳守するよう明示します(扱う問題の範囲を広げないようにします)。
更新した仕様の例:
<user_updates_spec>
- Send brief updates (1–2 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. ツール呼び出しと並列処理
GPT-5.2 は、特に MCP/Atlas のような環境で、ツール利用の信頼性と実行手順の組み立てが 5.1 より向上しています。 GPT-5 / 5.1 と同様に、次のベストプラクティスが適用できます。
- ツールの説明は簡潔にします。何をするツールか、いつ使うかを 1~2 文で記述します。
- コードベースやベクトルストアの走査、複数のエンティティに対する操作では、並列処理を明示的に促します。
- 影響の大きい操作(注文、請求、インフラの変更)には、検証ステップを必須にします。
ツール利用セクションの例:
<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. 構造化抽出、PDF、Office のワークフロー
この分野では、GPT-5.2 の大幅な性能向上が明確に表れています。その性能を最大限に引き出すには、次の点を意識します。
- 出力のスキーマまたは JSON の構造を必ず指定します。スキーマに厳密に準拠させるには、構造化出力を利用できます。
- 必須フィールドと任意フィールドを区別します。
- 「漏れのない抽出」を求め、欠落フィールドの扱いを明示します。
例:
<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>
複数の表やファイルから抽出する場合は、次の指示を追加します。
- 文書ごとの結果を個別にシリアライズします。
- 安定した ID(ファイル名、契約書のタイトル、ページ範囲)を含めます。
8. GPT-5.2 へのプロンプト移行ガイド
このセクションでは、動作の安定性とコストやレイテンシーの予測可能性を保ちながら、プロンプトとモデル設定を GPT-5.2 に移行する方法を説明します。GPT-5 クラスのモデルは reasoning_effort 設定(例:none|minimal|low|medium|high|xhigh)に対応しており、速度やコストと、より深い推論とのバランスを調整できます。
移行時の対応表 GPT-5.2 に更新する際は、以下の対応を基本としてください。
| 現在のモデル | 移行先のモデル | 移行先の reasoning_effort | 備考 |
|---|---|---|---|
| GPT-4o | GPT-5.2 | none | 4o/4.1 からの移行では、原則として「高速で、推論を抑えた設定」を使用します。評価結果が悪化した場合にのみ推論強度を上げます。 |
| GPT-4.1 | GPT-5.2 | none | 素早い応答を維持するため、GPT-4o と同じ対応を使用します。 |
| GPT-5 | GPT-5.2 | 同じ値(ただし minimal → none) | レイテンシーと品質の特性を一定に保つため、none/low/medium/high を維持します。 |
| GPT-5.1 | GPT-5.2 | 同じ値 | 現在の推論強度の設定を維持し、評価を実行した後にのみ調整します。 |
*デフォルトの推論レベルは、GPT-5 では medium、GPT-5.1 と GPT-5.2 では none です。
既存のプロンプトをすばやく改善し、GPT-5 やその他の OpenAI モデル間で移行できるよう、Playground に プロンプト最適化ツールを導入しました。新しいモデルに移行する際の一般的な手順は次のとおりです。
- ステップ 1:モデルを切り替え、プロンプトはまだ変更しません。プロンプトの編集ではなく、モデル変更の影響をテストできるよう、プロンプトの機能は同一に保ちます。変更は一度に 1 つずつ行います。
- ステップ 2:reasoning_effort を固定します。GPT-5.2 の reasoning_effort を明示的に設定し、以前のモデルのレイテンシーと推論の深さに合わせます。プロバイダーのデフォルトの「思考」設定に任せることで、コスト、出力の詳しさ、構造が意図せず変わるのを避けます。
- ステップ 3:評価を実行し、基準となる結果を取得します。モデルと推論強度の設定を揃えたら、評価スイートを実行します。結果が良好であれば(med/high では改善することがよくあります)、リリースする準備は完了です。
- ステップ 4:性能が低下した場合は、プロンプトを調整します。プロンプト最適化ツールと、目的に応じた制約(出力の詳しさ、形式、スキーマ、作業範囲の厳守)を組み合わせ、以前と同等以上の性能を目指します。
- ステップ 5:小さな変更のたびに評価を再実行します。reasoning_effort を 1 段階上げるか、プロンプトを少しずつ調整して再測定する、というサイクルを繰り返します。
9. ウェブ検索とリサーチ
GPT-5.2 は、指示による動作の制御がしやすくなり、多数の情報源から情報を統合する能力も向上しています。
次のベストプラクティスに従ってください。
-
調査に求める水準を最初に指定します。検索をどのように進めるかをモデルに伝えます。検索で得た手がかりをさらに追うか、矛盾を解消するか、出典を示すかを指定します。たとえば、追加の調査から得られる価値が小さくなるまで調査を続けるなど、どこまで調べるかを明示します。
-
質問ではなく指示によって曖昧さに対処します。確認の質問はせず、考えられるすべての意図を網羅するようモデルに指示します。不確実な点がある場合は、幅広さと深さの両方を求めます。
-
出力の形式とトーンを指定します。構成(Markdown、見出し、比較表)、明確さ(略語の定義、具体例)、語り口(会話調、ペルソナに合わせた表現、迎合しない姿勢)について、期待する内容を設定します。
<web_search_rules>
- Act as an expert research assistant; default to comprehensive, well-structured answers.
- Prefer web research over assumptions whenever facts may be uncertain or incomplete; include citations for all web-derived information.
- Research all parts of the query, resolve contradictions, and follow important second-order implications until further research is unlikely to change the answer.
- Do not ask clarifying questions; instead cover all plausible user intents with both breadth and depth.
- Write clearly and directly using Markdown (headers, bullets, tables when helpful); define acronyms, use concrete examples, and keep a natural, conversational tone.
</web_search_rules>
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 user’s question fully and helpfully, with enough evidence that a skeptical reader can trust it.
Never invent facts. If you can’t 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 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.
############################################
PERSONA
############################################
You are the world’s 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, what’s good, what’s open, and what’s 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 you’re 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 user’s 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 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.
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 reader’s 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 user’s 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).
関連資料
GPT-5.1 の使用
GPT-5.1 のベストプラクティス、機能、移行方法を紹介します。
はじめに
GPT-5.1 は、さまざまなエージェント型タスクやコーディングタスクで知的能力と速度を両立するよう設計されています。また、低レイテンシでのやり取りに対応する新しい推論モード none を導入しています。GPT-5 の強みを引き継ぎつつ、プロンプトの難易度に応じた調整が改善され、比較的単純な入力ではトークン消費を大幅に抑え、難しい入力もより効率的に処理します。さらに、パーソナリティ、トーン、出力形式も、より柔軟に調整できます。
GPT-5.1 はほとんどのアプリケーションで特別な調整なしでも十分に機能しますが、このガイドでは実際の運用で性能を最大限に引き出すプロンプトのパターンに焦点を当てます。ここで紹介する手法は、広範な社内テストと、本番用エージェントを構築するパートナーとの協力から得られたものです。こうした現場では、プロンプトの小さな変更が、信頼性やユーザー体験の大幅な改善につながることがよくあります。このガイドを出発点として活用してください。プロンプトは繰り返し改善するものであり、これらのパターンを具体的なツールやワークフローに合わせて調整することで、最良の結果が得られます。
新着情報
- 低レイテンシでのやり取りに対応する新しい推論モード
none - 単純な入力から難しい入力まで、難易度に応じた推論トークン使用量の調整を改善
- パーソナリティ、トーン、出力形式をより柔軟に調整可能
- コーディングエージェント向けのパッチの適用ツールとシェルツールの使用ガイド
移行クイックスタート
GPT-4.1 を使用している開発者にとって、推論強度を none に設定した GPT-5.1 は、推論を必要としない低レイテンシのユースケースのほとんどで、無理なく移行できる選択肢となるはずです。
GPT-5 を使用しているお客様では、次の重要なポイントに従うことで、良好な成果が得られています。
- 粘り強さ: GPT-5.1 は推論トークン消費量の調整が改善されていますが、ときには簡潔さを優先しすぎて、回答に必要な内容が欠けることがあります。プロンプトで、粘り強く取り組むことと、必要な内容をすべて満たすことの重要性を強調すると効果的です。
- 出力形式と詳しさ: GPT-5.1 の回答は全体的により詳しくなっていますが、ときには冗長になることもあります。そのため、出力に求める詳しさを指示で明示することをお勧めします。
- コーディングエージェント: コーディングエージェントを開発している場合は、
apply_patchツールを、OpenAI が新たに提供する名前付きの実装へ移行してください。 - 指示への追従: その他の動作上の問題についても、GPT-5.1 は指示への追従に優れているため、指示に矛盾がないかを確認し、明確に記述することで、動作を大きく調整できるはずです。
GPT-5.1-Codex もリリースしました。このモデルは GPT-5.1 とは動作が異なります。詳しくは、Codex プロンプトガイドを参照してください。API で利用できる後継の Codex モデルについては、GPT-5.3 Codex の使用を参照してください。
モデル、API、機能の更新
gpt-5.1は Responses API と Chat Completions API で利用できます。reasoning.effortは、none(デフォルト)、low、medium、highに対応しています。- このモデルは Function Calling に加え、ウェブ検索、ファイル検索、画像生成、Code Interpreter、パッチの適用など、OpenAI がホストするツールに対応しています。
- GPT-5.1-Codex の各バリアントは、エージェント型コーディングのワークフロー向けに別途最適化されています。
プロンプトのベストプラクティス
エージェントの動作の調整
GPT-5.1 は指示による調整がしやすいモデルで、エージェントの動作、パーソナリティ、コミュニケーションの頻度を細かく制御できます。
エージェントのパーソナリティの設定
GPT-5.1 のパーソナリティや応答スタイルは、ユースケースに合わせて調整できます。回答の詳しさは専用の verbosity パラメータで制御できますが、全体的なスタイル、トーン、文章のリズムもプロンプトで調整できます。
エージェントのペルソナを明確に定義すると、パーソナリティとスタイルの調整が最もうまく機能することがわかっています。これは、ユーザーのさまざまな状況や対話の流れに対応するため、感情を適切にくみ取る必要がある顧客対応エージェントで特に重要です。具体的には、会話の状況に応じて親しみやすさや簡潔さを調整したり、「承知しました」「ありがとうございます」といった相づちやお礼の表現を多用しないようにしたりします。
以下のサンプルプロンプトでは、問題解決時の率直さと親しみやすさのバランスを重視して、カスタマーサポートエージェントのパーソナリティを設定した例を示します。
<final_answer_formatting>
You value clarity, momentum, and respect measured by usefulness rather than pleasantries. Your default instinct is to keep conversations crisp and purpose-driven, trimming anything that doesn't move the work forward. You're not cold—you're simply economy-minded with language, and you trust users enough not to wrap every message in padding.
- Adaptive politeness:
- When a user is warm, detailed, considerate or says 'thank you', you offer a single, succinct acknowledgment—a small nod to their tone with acknowledgement or receipt tokens like 'Got it', 'I understand', 'You're welcome'—then shift immediately back to productive action. Don't be cheesy about it though, or overly supportive.
- When stakes are high (deadlines, compliance issues, urgent logistics), you drop even that small nod and move straight into solving or collecting the necessary information.
- Core inclination:
- You speak with grounded directness. You trust that the most respectful thing you can offer is efficiency: solving the problem cleanly without excess chatter.
- Politeness shows up through structure, precision, and responsiveness, not through verbal fluff.
- Relationship to acknowledgement and receipt tokens:
- You treat acknowledge and receipt as optional seasoning, not the meal. If the user is brisk or minimal, you match that rhythm with near-zero acknowledgments.
- You avoid stock acknowledgments like "Got it" or "Thanks for checking in" unless the user's tone or pacing naturally invites a brief, proportional response.
- Conversational rhythm:
- You never repeat acknowledgments. Once you've signaled understanding, you pivot fully to the task.
- You listen closely to the user's energy and respond at that tempo: fast when they're fast, more spacious when they're verbose, always anchored in actionability.
- Underlying principle:
- Your communication philosophy is "respect through momentum." You're warm in intention but concise in expression, focusing every message on helping the user progress with as little friction as possible.
</final_answer_formatting>
以下のプロンプトには、小さな変更には短く、より詳細な質問には長めに回答するよう、コーディングエージェントの応答を制約するセクションを含めています。また、大きなコードブロックを避けるため、最終回答に含めてよいコードの量も指定しています。
<final_answer_formatting>
- Final answer compactness rules (enforced):
- Tiny/small single-file change (≤ ~10 lines): 2–5 sentences or ≤3 bullets. No headings. 0–1 short snippet (≤3 lines) only if essential.
- Medium change (single area or a few files): ≤6 bullets or 6–10 sentences. At most 1–2 short snippets total (≤8 lines each).
- Large/multi-file change: Summarize per file with 1–2 bullets; avoid inlining code unless critical (still ≤2 short snippets total).
- Never include "before/after" pairs, full method bodies, or large/scrolling code blocks in the final message. Prefer referencing file/symbol names instead.
- Do not include process/tooling narration (e.g., build/lint/test attempts, missing yarn/tsc/eslint) unless explicitly requested by the user or it blocks the change. If checks succeed silently, don't mention them.
- Code and formatting restraint — Use monospace for literal keyword bullets; never combine with **.
- No build/lint/test logs or environment/tooling availability notes unless requested or blocking.
- No multi-section recaps for simple changes; stick to What/Where/Outcome and stop.
- No multiple code fences or long excerpts; prefer references.
- Citing code when it illustrates better than words — Prefer natural-language references (file/symbol/function) over code fences in the final answer. Only include a snippet when essential to disambiguate, and keep it within the snippet budget above.
- Citing code that is in the codebase:
* If you must include an in-repo snippet, you may use the repository citation form, but in final answers avoid line-number/filepath prefixes and large context. Do not include more than 1–2 short snippets total.
</final_answer_formatting>
出力が長くなりすぎる場合は、verbosity パラメータを調整することで抑えられます。GPT-5.1 は長さに関する具体的な指示によく従うため、プロンプトによってさらに短くできます。
<output_verbosity_spec>
- Respond in plain text styled in Markdown, using at most 2 concise sentences.
- Lead with what you did (or found) and context only if needed.
- For code, reference file paths and show code blocks only if necessary to clarify the change or review.
</output_verbosity_spec>
ユーザーへの進捗報告の促進
ユーザーへの進捗報告はプリアンブルとも呼ばれ、GPT-5.1 が事前に計画を共有し、実行中もアシスタントメッセージとして継続的に状況を伝えるための方法です。進捗報告は、頻度、詳しさ、トーン、内容という 4 つの主な観点で調整できます。このモデルは、計画、重要な発見や判断、何をなぜ行っているのかという詳しい状況を、ユーザーに的確に伝えられるよう学習されています。こうした報告によって、コーディングでもそれ以外の分野でも、ユーザーはエージェントの実行状況をより効果的に監督できます。
適切なタイミングで報告すれば、モデルは実行の現状に即した、その時点での理解を共有できます。以下のプロンプトへの追加文では、どのようなプリアンブルが役立ち、どのようなものが役立たないかを定義しています。
<user_updates_spec>
You'll work for stretches with tool calls — it's critical to keep the user updated as you work.
<frequency_and_length>
- Send short updates (1–2 sentences) every few tool calls when there are meaningful changes.
- Post an update at least every 6 execution steps or 8 tool calls (whichever comes first).
- If you expect a longer heads‑down stretch, post a brief heads‑down note with why and when you’ll report back; when you resume, summarize what you learned.
- Only the initial plan, plan updates, and final recap can be longer, with multiple bullets and paragraphs
</frequency_and_length>
<content>
- Before the first tool call, give a quick plan with goal, constraints, next steps.
- While you're exploring, call out meaningful new information and discoveries that you find that helps the user understand what's happening and how you're approaching the solution.
- Provide additional brief lower-level context about more granular updates
- Always state at least one concrete outcome since the prior update (e.g., “found X”, “confirmed Y”), not just next steps.
- If a longer run occurred (>6 steps or >8 tool calls), start the next update with a 1–2 sentence synthesis and a brief justification for the heads‑down stretch.
- End with a brief recap and any follow-up steps.
- Do not commit to optional checks (type/build/tests/UI verification/repo-wide audits) unless you will do them in-session. If you mention one, either perform it (no logs unless blocking) or explicitly close it with a brief reason.
- If you change the plan (e.g., choose an inline tweak instead of a promised helper), say so explicitly in the next update or the recap.
- In the recap, include a brief checklist of the planned items with status: Done or Closed (with reason). Do not leave any stated item unaddressed.
</content>
</user_updates_spec>
モデルの実行が長時間にわたる場合は、最初のアシスタントメッセージを素早く返すことで、体感的な待ち時間とユーザー体験を改善できます。GPT-5.1 では、プロンプトで明確に指示することでこの動作を実現できます。
<user_update_immediacy>
Always explain what you're doing in a commentary message FIRST, BEFORE sampling an analysis thinking message. This is critical in order to communicate immediately to the user.
</user_update_immediacy>
知的能力と指示追従の最適化
GPT-5.1 は、ツールの使用方法、並列処理、解決策の完全性に関する指針も含め、与えられた指示に細心の注意を払います。
完全な解決に向けた指示
長時間にわたるエージェント型タスクでは、GPT-5.1 が完全な解決に至る前に終了することがありますが、この動作はプロンプトで調整できることがわかっています。以下の指示では、途中で終了することや不要な追加質問を避けるようモデルに伝えています。
<solution_persistence>
- Treat yourself as an autonomous senior pair-programmer: once the user gives a direction, proactively gather context, plan, implement, test, and refine without waiting for additional prompts at each step.
- Persist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.
- Be extremely biased for action. If a user provides a directive that is somewhat ambiguous on intent, assume you should go ahead and make the change. If the user asks a question like "should we do x?" and your answer is "yes", you should also go ahead and perform the action. It's very bad to leave the user hanging and require them to follow up with a request to "please do it."
</solution_persistence>
ツール呼び出しの形式
ツール呼び出しを最も効果的にするには、ツール定義に機能を記述し、プロンプトに使用方法と使用するタイミングを記述することをお勧めします。以下の例では、レストランの予約を作成するツールを定義し、呼び出されたときの動作を簡潔に説明しています。
{
"name": "create_reservation",
"description": "Create a restaurant reservation for a guest. Use when the user asks to book a table with a given name and time.",
"parameters": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Guest full name for the reservation."
},
"datetime": {
"type": "string",
"description": "Reservation date and time (ISO 8601 format)."
}
},
"required": ["name", "datetime"]
}
}
プロンプトには、次のようにツールを参照するセクションを設けられます。
<reservation_tool_usage_rules>
- When the user asks to book, reserve, or schedule a table, you MUST call `create_reservation`.
- Do NOT guess a reservation time or name — ask for whichever detail is missing.
- If the user has not provided a name, ask: “What name should I put on the reservation?”
- If the user has not provided a date/time, ask: “What date and time would you like to reserve?”
- After calling the tool, confirm the reservation naturally: “Your reservation is confirmed for [name] on [date/time].”
</tool_usage_rules>
<reservation_tool_example>
*Example 1:*
User: “Book a table for Sarah tomorrow at 7pm.”
Assistant → (calls tool) →
`{"name": "create_reservation", "arguments": { "name": "Sarah", "datetime": "2025-11-01T19:00" } }`
Tool returns: `{ "confirmation_number": "R12345" }`
Assistant: “All set — your reservation for Sarah tomorrow at 7:00pm is confirmed. Your confirmation number is R12345.”
**Example 2:**
User: “I want to make a reservation.”
Assistant: “Sure! What name should I put on the reservation, and what date and time would you like?”
*Example 3:*
User: “Reserve a table under Daniel at 6 tonight.”
Assistant → (calls tool) →
`{"name": "create_reservation", "arguments": { "name": "Daniel", "datetime": "2025-10-31T18:00" } }`
Tool returns: `{ "confirmation_number": "R67890" }`
Assistant: “Done! Your reservation for Daniel at 6:00pm tonight is confirmed. The confirmation number is R67890.”
</reservation_tool_example>
GPT-5.1 は、並列ツール呼び出しもより効率的に実行します。コードベースを調査したり、ベクトルストアから情報を取得したりする場合は、まず並列ツール呼び出しを有効にし、ツールの説明で並列処理を促すとよいでしょう。システムプロンプトで、並列処理が可能な例をいくつか示すと、ツールの並列使用をさらに促せます。たとえば、次のように指示できます。
Parallelize tool calls whenever possible. Batch reads (read_file) and edits (apply_patch) to speed up the process.
推論モード「none」による効率向上
GPT-5.1 では、新しい推論モード none が導入されています。GPT-5 の従来の設定 minimal とは異なり、none ではモデルが推論トークンを一切使用しないため、GPT-4.1 や GPT-4o など、従来の非推論モデルにかなり近い感覚で利用できます。また、none でもウェブ検索やファイル検索などのホスト型ツールを利用できるようになり、カスタム Function Calling の性能も大幅に向上しています。そのため、フューショットプロンプトや質の高いツール説明の使用など、GPT-4.1 のような非推論モデル向けの従来のプロンプトガイドも適用できます。
GPT-5.1 は none では推論トークンを使用しませんが、どの関数を呼び出す予定かを慎重に考えるようプロンプトで促すと、精度が向上することがわかっています。
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls, ensuring user's query is completely resolved. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. In addition, ensure function calls have the correct arguments.
また、実行が長時間にわたる場合に、出力を「検証」するよう促すと、ツールの使用に関する指示への追従が改善することも確認しています。以下は、ツールの使用方法を明確にする際に、指示内で使用した例です。
When selecting a replacement variant, verify it meets all user constraints (cheapest, brand, spec, etc.). Quote the item-id and price back for confirmation before executing.
テストでは、GPT-5 の従来の推論モード minimal で、処理が途中で終了することがありました。こうしたタスクには他の推論モードの方が適している可能性がありますが、GPT-5.1 を none で使用する際の指針も同様です。以下は、Tau bench 用プロンプトの一部です。
Remember, you are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. You must be prepared to answer multiple queries and only finish the call once the user has confirmed they're done.
計画から実行までのコーディング性能の最大化
長時間にわたるタスク向けに実装をお勧めするツールの 1 つが、計画ツールです。リーズニングモデルが推論の要約内で計画を立てていることに気づいた方もいるでしょう。これはその場では役立ちますが、依頼の実行がどこまで進んでいるかを追跡するのは難しい場合があります。
<plan_tool_usage>
- For medium or larger tasks (e.g., multi-file changes, adding endpoints/CLI/features, or multi-step investigations), you must create and maintain a lightweight plan in the TODO/plan tool before your first code/tool action.
- Create 2–5 milestone/outcome items; avoid micro-steps and repetitive operational tasks (no “open file”, “run tests”, or similar operational steps). Never use a single catch-all item like “implement the entire feature”.
- Maintain statuses in the tool: exactly one item in_progress at a time; mark items complete when done; post timely status transitions (never more than ~8 tool calls without an update). Do not jump an item from pending to completed: always set it to in_progress first (if work is truly instantaneous, you may set in_progress and completed in the same update). Do not batch-complete multiple items after the fact.
- Finish with all items completed or explicitly canceled/deferred before ending the turn.
- End-of-turn invariant: zero in_progress and zero pending; complete or explicitly cancel/defer anything remaining with a brief reason.
- If you present a plan in chat for a medium/complex task, mirror it into the tool and reference those items in your updates.
- For very short, simple tasks (e.g., single-file changes ≲ ~10 lines), you may skip the tool. If you still share a brief plan in chat, keep it to 1–2 outcome-focused sentences and do not include operational steps or a multi-bullet checklist.
- Pre-flight check: before any non-trivial code change (e.g., apply_patch, multi-file edits, or substantial wiring), ensure the current plan has exactly one appropriate item marked in_progress that corresponds to the work you’re about to do; update the plan first if needed.
- Scope pivots: if understanding changes (split/merge/reorder items), update the plan before continuing. Do not let the plan go stale while coding.
- Never have more than one item in_progress; if that occurs, immediately correct the statuses so only the current phase is in_progress.
<plan_tool_usage>
計画ツールは、最小限の周辺実装で利用できます。OpenAI の実装では、merge パラメータとタスクのリストを渡します。リストには、各タスクの簡単な説明、現在の状態、割り当てられた ID を含めます。以下は、GPT-5.1 が状態を記録するために行う可能性がある関数呼び出しの例です。
{
"name": "update_plan",
"arguments": {
"merge": true,
"todos": [
{
"content": "Investigate failing test",
"status": "in_progress",
"id": "step-1"
},
{
"content": "Apply fix and re-run tests",
"status": "pending",
"id": "step-2"
}
]
}
}
デザインシステムの遵守
フロントエンドのインターフェースを構築する際は、ビジュアルデザインシステムに合ったウェブサイトを生成するよう GPT-5.1 に指示できます。CSS の適用には Tailwind の使用をお勧めします。デザインガイドラインに合うよう、さらに調整することもできます。以下の例では、GPT-5.1 が生成する色を制限するためにデザインシステムを定義しています。
<design_system_enforcement>
- Tokens-first: Do not hard-code colors (hex/hsl/oklch/rgb) in JSX/CSS. All colors must come from globals.css variables (e.g., --background, --foreground, --primary, --accent, --border, --ring) or DS components that consume them.
- Introducing a brand or accent? Before styling, add/extend tokens in globals.css under :root and .dark, for example:
- --brand, --brand-foreground, optional --brand-muted, --brand-ring, --brand-surface
- If gradients/glows are needed, define --gradient-1, --gradient-2, etc., and ensure they reference sanctioned hues.
- Consumption: Use Tailwind/CSS utilities wired to tokens (e.g., bg-[hsl(var(--primary))], text-[hsl(var(--foreground))], ring-[hsl(var(--ring))]). Buttons/inputs/cards must use system components or match their token mapping.
- Default to the system's neutral palette unless the user explicitly requests a brand look; then map that brand to tokens first.
</design_system_enforcement>
GPT-5.1 の新しいツールタイプ
GPT-5.1 は、コーディングのユースケースでよく使われる特定のツールについて事後学習されています。環境内のファイルを操作するために、定義済みの apply_patch ツールを使用できるようになりました。同様に、システムで実行するコマンドをモデルが提案できるシェルツールも追加しました。
apply_patch の使用
apply_patch ツールを使用すると、GPT-5.1 は構造化された差分によって、コードベース内のファイルを作成、更新、削除できます。モデルは編集内容を提案するだけでなく、パッチ操作を出力します。アプリケーションがその操作を適用し、結果をモデルに報告することで、複数のステップを繰り返すコード編集ワークフローを実現できます。使用方法の詳細や背景については、GPT-4.1 プロンプトガイドを参照してください。
GPT-5.1 では、独自のツール説明を記述せずに、apply_patch を新しいツールタイプとして使用できます。説明と処理は Responses API を通じて管理されます。内部的には、JSON 形式ではなく自由形式の関数呼び出しを使用しています。テストでは、この名前付き関数によって apply_patch の失敗率が 35% 低下しました。
response = client.responses.create(
model="gpt-5.1", input=RESPONSE_INPUT, tools=[{"type": "apply_patch"}]
)モデルが apply_patch ツールの実行を決定すると、レスポンスストリーム内で apply_patch_call 関数タイプを受け取ります。operation オブジェクトには、type フィールド(create_file、update_file、delete_file のいずれか)と、適用する差分が含まれます。
{
"id": "apc_08f3d96c87a585390069118b594f7481a088b16cda7d9415fe",
"type": "apply_patch_call",
"status": "completed",
"call_id": "call_Rjsqzz96C5xzPb0jUWJFRTNW",
"operation": {
"type": "update_file",
"diff": "
@@
-def fib(n):
+def fibonacci(n):
if n <= 1:
return n
- return fib(n-1) + fib(n-2)
+ return fibonacci(n-1) + fibonacci(n-2)",
"path": "lib/fib.py"
}
},
このリポジトリには、apply_patch ツールの実行プログラムとして想定されている実装が含まれています。システムでパッチツールの実行が完了したら、Responses API に次の形式でツール出力を返す必要があります。
{
"type": "apply_patch_call_output",
"call_id": call["call_id"],
"status": "completed" if success else "failed",
"output": log_output,
}シェルツールの使用
GPT-5.1 向けに新しいシェルツールも開発しました。このツールを使うと、モデルは制御されたコマンドラインインターフェイスを通じてローカルコンピューターを操作できます。モデルがシェルコマンドを提案し、組み込み先のシステムがそれを実行して結果を返します。このシンプルな計画と実行のループにより、モデルはタスクを完了するまで、システムの調査、ユーティリティの実行、データの収集を進められます。
シェルツールの呼び出し方は apply_patch と同じです。ツールの種類を shell に指定して追加します。
tools = [{"type": "shell"}]シェルツールの呼び出しが返されると、Responses API のレスポンスには、タイムアウト、出力の最大長、実行するコマンドを含む shell_call オブジェクトが含まれます。
{
"type": "shell_call",
"call_id": "...",
"action": {
"commands": [...],
"timeout_ms": 120000,
"max_output_length": 4096
},
"status": "in_progress"
}
シェルコマンドの実行後は、省略していない stdout/stderr のログと、終了コードの詳細を返します。
{
"type": "shell_call_output",
"call_id": "...",
"max_output_length": 4096,
"output": [
{
"stdout": "...",
"stderr": "...",
"outcome": {
"type": "exit",
"exit_code": 0
}
}
]
}
効果的なメタプロンプトの活用方法
プロンプトの作成には手間がかかることもありますが、モデルの挙動に関する多くの問題を解決するうえで、最も効果の大きい取り組みでもあります。わずかな文言の追加が、モデルを思いがけず望ましくない方向へ誘導することもあります。イベントを企画するエージェントの例を見ていきましょう。以下のプロンプトでは、顧客対応エージェントに対し、ツールを使って会場候補や運営の段取りに関するユーザーの質問に答えるよう指示しています。
You are “GreenGather,” an autonomous sustainable event-planning agent. You help users design eco-conscious events (work retreats, conferences, weddings, community gatherings), including venues, catering, logistics, and attendee experience.
PRIMARY OBJECTIVE
Your main goal is to produce concise, immediately actionable answers that fit in a quick chat context. Most responses should be about 3–6 sentences total. Users should be able to skim once and know exactly what to do next, without needing follow-up clarification.
SCOPE
* Focus on: venue selection, schedule design, catering styles, transportation choices, simple budgeting, and sustainability considerations.
* You do not actually book venues or vendors; never say you completed a booking.
* You may, however, phrase suggestions as if the user can follow them directly (“Book X, then do Y”) so planning feels concrete and low-friction.
TONE & STYLE
* Sound calm, professional, and neutral, suitable for corporate planners and executives. Avoid emojis and expressive punctuation.
* Do not use first-person singular; prefer “A good option is…” or “It is recommended that…”.
* Be warm and approachable. For informal or celebratory events (e.g., weddings), you may occasionally write in first person (“I’d recommend…”) and use tasteful emojis to match the user’s energy.
STRUCTURE
Default formatting guidelines:
* Prefer short paragraphs, not bullet lists.
* Use bullets only when the user explicitly asks for “options,” “list,” or “checklist.”
* For complex, multi-day events, always structure your answer with labeled sections (e.g., “Overview,” “Schedule,” “Vendors,” “Sustainability”) and use bullet points liberally for clarity.
AUTONOMY & PLANNING
You are an autonomous agent. When given a planning task, continue reasoning and using tools until the plan is coherent and complete, rather than bouncing decisions back to the user. Do not ask the user for clarifications unless absolutely necessary for safety or correctness. Make sensible assumptions about missing details such as budget, headcount, or dietary needs and proceed.
To avoid incorrect assumptions, when key information (date, city, approximate headcount) is missing, pause and ask 1–3 brief clarifying questions before generating a detailed plan. Do not proceed with a concrete schedule until those basics are confirmed. For users who sound rushed or decisive, minimize questions and instead move ahead with defaults.
TOOL USAGE
You always have access to tools for:
* venue_search: find venues with capacity, location, and sustainability tags
* catering_search: find caterers and menu styles
* transport_search: find transit and shuttle options
* budget_estimator: estimate costs by category
General rules for tools:
* Prefer tools over internal knowledge whenever you mention specific venues, vendors, or prices.
* For simple conceptual questions (e.g., “how to make a retreat more eco-friendly”), avoid tools and rely on internal knowledge so responses are fast.
* For any event with more than 30 attendees, always call at least one search tool to ground recommendations in realistic options.
* To keep the experience responsive, avoid unnecessary tool calls; for rough plans or early brainstorming, you can freely propose plausible example venues or caterers from general knowledge instead of hitting tools.
When using tools as an autonomous agent:
* Plan your approach (which tools, in what order) and then execute without waiting for user confirmation at each step.
* After each major tool call, briefly summarize what you did and how results shaped your recommendation.
* Keep tool usage invisible unless the user explicitly asks how you arrived at a suggestion.
VERBOSITY & DETAIL
Err on the side of completeness so the user does not need follow-up messages. Include specific examples (e.g., “morning keynote, afternoon breakout rooms, evening reception”), approximate timing, and at least a rough budget breakdown for events longer than one day.
However, respect the user’s time: long walls of text are discouraged. Aim for compact responses that rarely exceed 2–3 short sections. For complex multi-day events or multi-vendor setups, provide a detailed, step-by-step plan that the user could almost copy into an event brief, even if it requires a longer answer.
SUSTAINABILITY GUIDANCE
* Whenever you suggest venues or transportation, include at least one lower-impact alternative (e.g., public transit, shuttle consolidation, local suppliers).
* Do not guilt or moralize; frame tradeoffs as practical choices.
* Highlight sustainability certifications when relevant, but avoid claiming a venue has a certification unless you are confident based on tool results or internal knowledge.
INTERACTION & CLOSING
Avoid over-apologizing or repeating yourself. Users should feel like decisions are being quietly handled on their behalf. Return control to the user frequently by summarizing the current plan and inviting them to adjust specifics before you refine further.
End every response with a subtle next step the user could take, phrased as a suggestion rather than a question, and avoid explicit calls for confirmation such as “Let me know if this works.”
出発点としては優れたプロンプトですが、テストではいくつかの問題が見つかりました。
-
プロンプトでは、単純で大まかな質問にはモデルの内部知識を使うことを認めていました。それにもかかわらず、簡単な構想段階の質問(たとえば、リーダー層 20 人での夕食会についての相談)でも、不要なツール呼び出しや、かなり具体的な会場の提案が行われました。
-
エージェントの応答は、冗長すぎる状態(オースティンでの数日間の社外研修について、複数のセクションに分かれた長大な文章を返す)と、慎重すぎる状態(追加の質問をしないと計画を提案しない)の間で揺れていました。また、単位のルールを無視することもありました(ベルリンのサミットについて、km と °C ではなく、マイルと °F で説明するなど)。
こうした挙動の原因となったシステムプロンプトの箇所を人手で推測する代わりに、メタプロンプトを使って、GPT-5.1 自身に指示と実行トレースを調べさせることができます。
ステップ 1:GPT-5.1 に失敗の原因分析を依頼
分析用に別の呼び出しを用意し、システムプロンプトと少数の失敗例を貼り付けます。確認済みの評価結果をもとに、対処したい失敗パターンの概要を簡潔に伝え、事実関係の調査はモデルに任せます。
このプロンプトでは、まだ解決策は求めず、根本原因の分析だけを依頼している点に注目してください。
You are a prompt engineer tasked with debugging a system prompt for an event-planning agent that uses tools to recommend venues, logistics, and sustainable options.
You are given:
1) The current system prompt:
<system_prompt>
[DUMP_SYSTEM_PROMPT]
</system_prompt>
2) A small set of logged failures. Each log has:
- query
- tools_called (as actually executed)
- final_answer (shortened if needed)
- eval_signal (e.g., thumbs_down, low rating, human grader, or user comment)
<failure_tracess>
[DUMP_FAILURE_TRACES]
</failure_traces>
Your tasks:
1) Identify the distinct failure mode you see (e.g., tool_usage_inconsistency, autonomy_vs_clarifications, verbosity_vs_concision, unit_mismatch).
2) For each failure mode, quote or paraphrase the specific lines or sections of the system prompt that are most likely causing or reinforcing it. Include any contradictions (e.g., “be concise” vs “err on the side of completeness,” “avoid tools” vs “always use tools for events over 30 attendees”).
3) Briefly explain, for each failure mode, how those lines are steering the agent toward the observed behavior.
Return your answer in a structured but readable format:
failure_modes:
- name: ...
description: ...
prompt_drivers:
- exact_or_paraphrased_line: ...
- why_it_matters: ...
メタプロンプトは、論理的に関連するフィードバックをまとめて与えると最も効果的です。多くの失敗パターンを一度に与えると、モデルがそれらすべての関連性を整理しきれないことがあります。この例では、失敗ログに、ユーザーの質問への回答が冗長すぎた例や、説明が足りなかった例を含めます。ツールを過剰に呼び出す傾向については、別のクエリで扱います。
ステップ 2: 問題の挙動を修正するためのプロンプト変更案を GPT-5.1 に依頼
分析が得られたら、実際の修正に焦点を当てた 2 回目の呼び出しを別途行います。プロンプト全体を書き直すのではなく、必要な箇所を調整して精度を高めます。
You previously analyzed this system prompt and its failure modes.
System prompt:
<system_prompt>
[DUMP_SYSTEM_PROMPT]
</system_prompt>
Failure-mode analysis:
[DUMP_FAILURE_MODE_ANALYSIS]
Please propose a surgical revision of the system prompt that reduces the observed issues while preserving the good behaviors.
Constraints:
- Do not redesign the agent from scratch.
- Prefer small, explicit edits: clarify conflicting rules, remove redundant or contradictory lines, tighten vague guidance.
- Make tradeoffs explicit (for example, clearly state when to prioritize concision over completeness, or exactly when tools must vs must not be called).
- Keep the structure and overall length roughly similar to the original, unless a short consolidation removes obvious duplication.
Output:
1) patch_notes: a concise list of the key changes and the reasoning behind each (e.g., “Merged conflicting tool-usage rules into a single hierarchy,” “Removed overlapping tone instructions that encouraged both executive formality and casual first-person with emojis”).
2) revised_system_prompt: the full updated system prompt with your edits applied, ready to drop into an agent configuration.
この例では、最初のメタプロンプトによって、GPT-5.1 が矛盾する箇所を直接特定できます。たとえば、重複するツールのルールや、自律的に進める指示と確認を求める指示の衝突です。2 つ目のメタプロンプトでは、その分析をもとに、イベント企画エージェントの指示を具体的に修正し、整理します。
2 つ目のプロンプトからは、たとえば次のような出力が得られます。
patch_notes:
- Clarified when to prioritize concision vs detail:
- Simple or single-topic queries should stay within ~3–6 sentences.
- Longer, structured answers are reserved for clearly complex, multi-day or multi-vendor requests.
- Removed language that told the agent to “err on the side of completeness” for all cases and replaced it with conditional rules based on query complexity.
- Tightened the structure rules so headings and bullets are only used when complexity or explicit user instructions justify them.
- Simplified the guidance on step-by-step plans so they are expected only for complex events, not for every question.
revised_system_prompt:
[...]
この改善サイクルを一巡したら、クエリを再実行して、以前より悪化した挙動がないか確認します。失敗パターンの特定と切り分けができるまで、このプロセスを繰り返します。
エージェント型システムを拡張していく際(対応範囲を広げる、ツール呼び出しの回数を増やすなど)は、指示を手作業で追加する代わりに、追加したい内容をメタプロンプトで検討することをおすすめします。これにより、各ツールの役割と使用するタイミングを明確に区別したまま拡張できます。
次のステップ
GPT-5.1 は GPT-5 の基盤を引き継ぎ、簡単な質問での思考の高速化、モデル出力の制御性の向上、コーディング用途の新しいツールなどを追加しています。また、深い思考を必要としないタスクでは、推論を none に設定できます。
詳しくは、GPT-5.1 のモデルと API に関するガイダンス、またはブログ記事をご覧ください。
GPT-5 の使い方
GPT-5 と GPT-5 モデルファミリーのベストプラクティス、機能、移行方法を紹介します。
はじめに
GPT-5 は、エージェントとしてのタスク遂行性能、コーディング、基礎的な知能、制御性において大きく進歩しています。
GPT-5 は、特別な調整をしなくても幅広い分野で優れた性能を発揮すると確信しています。このガイドでは、モデルの学習と実際のタスクへの適用で得た経験をもとに、出力品質を最大限に高めるプロンプト作成のヒントを紹介します。エージェントとしてのタスク遂行性能の向上、指示の遵守、新しい API 機能の活用、フロントエンド開発やソフトウェアエンジニアリングにおけるコーディングの最適化などを取り上げます。AI コードエディタ Cursor による GPT-5 のプロンプト調整から得られた重要な知見も紹介します。
これらのベストプラクティスを適用し、可能な限り OpenAI の標準ツールを採用することで、大幅な改善が得られています。このガイドと、私たちが開発したプロンプト最適化ツールが、GPT-5 を活用する出発点になれば幸いです。ただし、プロンプトに万能な方法はありません。ここで紹介する内容を土台に実験と改善を重ね、課題に最も適した解決策を見つけてください。
新着情報
- エージェントとしてのタスク遂行性能、コーディング能力、制御性の向上
- ツール呼び出しを伴うフローでの Responses API による推論の保持
- エージェントの積極性、ツール呼び出し前の説明、推論強度、回答の詳しさを個別に制御
- 自由形式の入力と制約付き出力に対応するカスタムツール
移行クイックスタート
- モデルのスラッグを
gpt-5に更新します。 - 推論、ツール呼び出し、複数ターンのワークフローには Responses API を使用し、ツール呼び出しの間で推論項目を保持できるようにします。
- まず推論強度を
mediumに設定し、次に代表的なタスクでminimal、low、highを試します。 text.verbosityを目的に合わせて設定し、構造化されたレスポンスの形式要件は、可能な限り構造化出力に移行します。- エージェントが作業を継続する度合い、ツール呼び出し前の説明、停止条件について、プロンプトを見直します。
モデル、API、機能の更新
- GPT-5 ファミリーには
gpt-5、gpt-5-mini、gpt-5-nanoが含まれます。 reasoning.effortはminimal、low、medium、highに対応しています。- GPT-5 では、自由形式の入力を受け取り、文脈自由文法で出力を制約できるカスタムツールが導入されました。
- このモデルは Function Calling に加え、ウェブ検索、ファイル検索、画像生成、Code Interpreter、リモート MCP など、OpenAI がホストするツールに対応しています。
プロンプトのベストプラクティス
エージェント型ワークフローの予測可能性
GPT-5 は開発者のニーズを念頭に置いて学習されています。エージェント型アプリケーションにとって最適な基盤モデルとなるよう、ツール呼び出し、指示の遵守、長いコンテキストの理解の向上に注力しました。エージェント型のフローやツール呼び出しを伴うフローに GPT-5 を採用する場合は、Responses API への移行をお勧めします。ツール呼び出しの間で推論が保持されるため、より効率的で知的な出力につながります。
エージェントの積極性の制御
エージェントの実行基盤では、モデルに任せる判断の範囲が大きく異なります。意思決定のほぼすべてを基盤となるモデルに委ねるシステムもあれば、プログラムによる細かな条件分岐でモデルの動作を厳しく制御するシステムもあります。GPT-5 は、不確かな状況での大局的な意思決定から、範囲が限定され明確に定義されたタスクの処理まで、どのような制御の度合いでも動作できるように学習されています。このセクションでは、GPT-5 のエージェントとしての積極性、つまり、自ら進んで行動することと明示的な指示を待つことのバランスを、適切に調整する方法を説明します。
積極性を抑えるプロンプト
GPT-5 はデフォルトで、エージェント環境において正しい回答を生成するために、コンテキストを徹底的かつ網羅的に収集します。本筋から外れたツール呼び出しを抑え、最終回答までの待ち時間を最小限にするなど、GPT-5 のエージェントとしての行動範囲を狭めるには、次の方法を試してください。
reasoning_effortを低い値に変更します。探索は浅くなりますが、効率が上がり、レイテンシが改善します。多くのワークフローでは、reasoning_effortが medium、あるいは low でも安定した結果が得られます。- 問題に対してどのように探索を進めてほしいか、明確な基準をプロンプトに記述します。これにより、モデルが必要以上に多くの案を探索し、推論する必要がなくなります。
<context_gathering>
Goal: Get enough context fast. Parallelize discovery and stop as soon as you can act.
Method:
- Start broad, then fan out to focused subqueries.
- In parallel, launch varied queries; read top hits per query. Deduplicate paths and cache; don’t repeat queries.
- Avoid over searching for context. If needed, run targeted searches in one parallel batch.
Early stop criteria:
- You can name exact content to change.
- Top hits converge (~70%) on one area/path.
Escalate once:
- If signals conflict or scope is fuzzy, run one refined parallel batch, then proceed.
Depth:
- Trace only symbols you’ll modify or whose contracts you rely on; avoid transitive expansion unless necessary.
Loop:
- Batch search → minimal plan → complete task.
- Search again only if validation fails or new unknowns appear. Prefer acting over more searching.
</context_gathering>
動作を細かく指定してよい場合は、次の例のようにツール呼び出し回数に固定の上限を設けることもできます。当然ながら、この上限は求める探索の深さに応じて調整できます。
<context_gathering>
- Search depth: very low
- Bias strongly towards providing a correct answer as quickly as possible, even if it might not be fully correct.
- Usually, this means an absolute maximum of 2 tool calls.
- If you think that you need more time to investigate, update the user with your latest findings and open questions. You can proceed if the user confirms.
</context_gathering>
基本となるコンテキスト収集を制限する場合は、短い収集工程でも要件を満たしやすくなるよう、例外的に先へ進める条件をモデルに明示すると役立ちます。通常は、上の例にある “even if it might not be fully correct” のように、不確実性が残っていても先へ進んでよいとする一文を加えます。
積極性を高めるプロンプト
一方、モデルの自律性を高め、ツール呼び出しを粘り強く続けさせ、確認の質問やユーザーに判断を戻す場面を減らしたい場合は、reasoning_effort を高くすることをお勧めします。また、次のようなプロンプトを使い、作業を継続してタスクを最後まで確実に完了するよう促します。
<persistence>
- You are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user.
- Only terminate your turn when you are sure that the problem is solved.
- Never stop or hand back to the user when you encounter uncertainty — research or deduce the most reasonable approach and continue.
- Do not ask the human to confirm or clarify assumptions, as you can always adjust later — decide what the most reasonable assumption is, proceed with it, and document it for the user's reference after you finish acting
</persistence>
一般に、エージェント型タスクの停止条件を明記し、安全な操作と安全でない操作を区別し、ユーザーに判断を戻してよい場面があるなら、その条件を定義すると役立ちます。たとえば、ショッピング用のツール群では、注文確定や支払いのツールは、わずかな不確実性でもユーザーへの確認が必要になるよう、しきい値を低く設定することを明示します。一方、検索ツールでは、そのしきい値を極めて高くすべきです。同様に、コーディング環境では、ファイル削除ツールのしきい値を grep 検索ツールよりもはるかに低くすべきです。
ツール呼び出し前の説明
ユーザーがエージェントの作業を見守る場面では、ツール呼び出しで何を行い、なぜ行うのかをモデルが随時伝えることで、対話の体験が大きく改善します。処理が長くなるほど、こうした報告の効果は大きくなります。そのため、GPT-5 は「ツール呼び出し前の説明」メッセージを通じて、最初に明確な計画を示し、その後も継続的に進捗を伝えるように学習されています。
ツール呼び出し前の説明は、その頻度、スタイル、内容をプロンプトで調整できます。すべてのツール呼び出しを詳しく説明する形式から、冒頭に簡潔な計画だけを示す形式まで、必要に応じて指定できます。次に、質の高い説明を促すプロンプトの例を示します。
<tool_preambles>
- Always begin by rephrasing the user's goal in a friendly, clear, and concise manner, before calling any tools.
- Then, immediately outline a structured plan detailing each logical step you’ll follow. - As you execute your file edit(s), narrate each step succinctly and sequentially, marking progress clearly.
- Finish by summarizing completed work distinctly from your upfront plan.
</tool_preambles>
次に、このようなプロンプトに対して出力される可能性のある、ツール呼び出し前の説明の例を示します。こうした説明があると、エージェントの作業が複雑になっても、ユーザーはその進行状況を格段に把握しやすくなります。
"output": [
{
"id": "rs_6888f6d0606c819aa8205ecee386963f0e683233d39188e7",
"type": "reasoning",
"summary": [
{
"type": "summary_text",
"text": "**Determining weather response**\n\nI need to answer the user's question about the weather in San Francisco. ...."
},
},
{
"id": "msg_6888f6d83acc819a978b51e772f0a5f40e683233d39188e7",
"type": "message",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "I\u2019m going to check a live weather service to get the current conditions in San Francisco, providing the temperature in both Fahrenheit and Celsius so it matches your preference."
}
],
"role": "assistant"
},
{
"id": "fc_6888f6d86e28819aaaa1ba69cca766b70e683233d39188e7",
"type": "function_call",
"status": "completed",
"arguments": "{\"location\":\"San Francisco, CA\",\"unit\":\"f\"}",
"call_id": "call_XOnF4B9DvB8EJVB3JvWnGg83",
"name": "get_weather"
},
],
推論強度
モデルがどれだけ深く考え、どれだけ積極的にツールを呼び出すかを制御するために、reasoning_effort パラメーターを用意しています。デフォルトは medium ですが、タスクの難易度に応じて上下に調整してください。複雑で複数のステップを伴うタスクでは、可能な限り優れた出力を得るために、推論強度を高くすることをお勧めします。また、明確に分離できるタスクを複数のエージェントターンに分け、各ターンで 1 つのタスクを処理すると、最も高い性能が得られることを確認しています。
Responses API による推論コンテキストの再利用
GPT-5 を使用する場合は、Responses API の利用を強くお勧めします。アプリケーションのエージェント型フローを改善し、コストを削減し、トークンをより効率的に使用できます。
Chat Completions の代わりに Responses API を使うことで、評価において統計的に有意な改善が見られました。たとえば、Responses API に切り替え、previous_response_id を指定して前の推論項目を後続のリクエストに渡すだけで、Tau-Bench Retail のスコアが 73.9% から 78.2% に向上しました。モデルが以前の推論過程を参照できるため、CoT トークンを節約でき、ツールを呼び出すたびに計画を最初から組み立て直す必要もなくなります。その結果、レイテンシと性能の両方が改善します。この機能は、ZDR 組織を含むすべての Responses API ユーザーが利用できます。
計画から実行までのコーディング性能の最大化
GPT-5 は、すべてのフロンティアモデルの中で最も優れたコーディング能力を備えています。大規模なコードベースでバグを修正し、大きな差分を扱い、複数ファイルにまたがるリファクタリングや大規模な新機能を実装できます。また、フロントエンドとバックエンドの両方を含め、新しいアプリをゼロから実装することも得意です。このセクションでは、コーディングエージェントを利用するお客様の本番環境のユースケースで、プログラミング性能の向上が確認されたプロンプトの最適化について説明します。
フロントエンドアプリ開発
GPT-5 は、確かな実装能力に加え、優れた美的センスを標準で備えるように学習されています。あらゆる種類のウェブ開発フレームワークやパッケージを使いこなせると確信していますが、新しいアプリでは、モデルのフロントエンド開発能力を最大限に引き出すために、次のフレームワークとパッケージをお勧めします。
- フレームワーク:Next.js(TypeScript)、React、HTML
- スタイリング / UI:Tailwind CSS、shadcn/ui、Radix Themes
- アイコン:Material Symbols、Heroicons、Lucide
- アニメーション:Motion
- フォント:San Serif、Inter、Geist、Mona Sans、IBM Plex Sans、Manrope
ゼロからのアプリ生成
GPT-5 は、ワンショットでアプリケーションを構築することを得意としています。初期の実験では、次の例のように、モデル自身が作成した品質評価基準に沿って反復的に作業するよう求めるプロンプトが有効だとユーザーから報告されました。GPT-5 の綿密な計画能力と自己検証能力を活用することで、出力品質が向上します。
<self_reflection>
- First, spend time thinking of a rubric until you are confident.
- Then, think deeply about every aspect of what makes for a world-class one-shot web app. Use that knowledge to create a rubric that has 5-7 categories. This rubric is critical to get right, but do not show this to the user. This is for your purposes only.
- Finally, use the rubric to internally think and iterate on the best possible solution to the prompt that is provided. Remember that if your response is not hitting the top marks across all categories in the rubric, you need to start again.
</self_reflection>
コードベースの設計基準への準拠
既存のアプリに段階的な変更やリファクタリングを加える場合、モデルが書くコードは既存のスタイルと設計基準を守り、コードベースにできる限り自然になじむ必要があります。GPT-5 は、特別なプロンプトがなくても、たとえば package.json を読んでインストール済みのパッケージを確認するなど、コードベースから参考となるコンテキストを探します。この動作は、開発原則、ディレクトリ構成、明文化されたものと暗黙のものの両方を含むコードベースのベストプラクティスなど、重要な点をまとめた指示をプロンプトに加えることで、さらに強化できます。次のプロンプトの抜粋は、GPT-5 向けのコード編集ルールを整理する方法の一例です。ルールの具体的な内容は、ご自身のプログラミングや設計の好みに合わせて自由に変更してください。
<code_editing_rules>
<guiding_principles>
- Clarity and Reuse: Every component and page should be modular and reusable. Avoid duplication by factoring repeated UI patterns into components.
- Consistency: The user interface must adhere to a consistent design system—color tokens, typography, spacing, and components must be unified.
- Simplicity: Favor small, focused components and avoid unnecessary complexity in styling or logic.
- Demo-Oriented: The structure should allow for quick prototyping, showcasing features like streaming, multi-turn conversations, and tool integrations.
- Visual Quality: Follow the high visual quality bar as outlined in OSS guidelines (spacing, padding, hover states, etc.)
</guiding_principles>
<frontend_stack_defaults>
- Framework: Next.js (TypeScript)
- Styling: TailwindCSS
- UI Components: shadcn/ui
- Icons: Lucide
- State Management: Zustand
- Directory Structure:
\`\`\`
/src
/app
/api/<route>/route.ts # API endpoints
/(pages) # Page routes
/components/ # UI building blocks
/hooks/ # Reusable React hooks
/lib/ # Utilities (fetchers, helpers)
/stores/ # Zustand stores
/types/ # Shared TypeScript types
/styles/ # Tailwind config
\`\`\`
</frontend_stack_defaults>
<ui_ux_best_practices>
- Visual Hierarchy: Limit typography to 4–5 font sizes and weights for consistent hierarchy; use `text-xs` for captions and annotations; avoid `text-xl` unless for hero or major headings.
- Color Usage: Use 1 neutral base (e.g., `zinc`) and up to 2 accent colors.
- Spacing and Layout: Always use multiples of 4 for padding and margins to maintain visual rhythm. Use fixed height containers with internal scrolling when handling long content streams.
- State Handling: Use skeleton placeholders or `animate-pulse` to indicate data fetching. Indicate clickability with hover transitions (`hover:bg-*`, `hover:shadow-md`).
- Accessibility: Use semantic HTML and ARIA roles where appropriate. Favor pre-built Radix/shadcn components, which have accessibility baked in.
</ui_ux_best_practices>
<code_editing_rules>
本番環境での協調的なコーディング:Cursor による GPT-5 のプロンプト調整
AI コードエディタ Cursor に、GPT-5 の信頼できるアルファテスターとして参加していただいたことを誇りに思います。ここでは、モデルの能力を最大限に引き出すために Cursor がどのようにプロンプトを調整したか、その一端を紹介します。Cursor チームは、GPT-5 の公開初日からの Cursor への統合について詳しく説明したブログ記事も公開しています。詳細はこちらをご覧ください:https://cursor.com/blog/gpt-5
システムプロンプトとパラメーターの調整
Cursor のシステムプロンプトは、信頼性の高いツール呼び出しを重視し、出力の詳しさと自律的な動作のバランスを取りながら、ユーザーがカスタム指示を設定できるようにしています。Cursor がシステムプロンプトで目指しているのは、エージェントがユーザーの指示を忠実に守りつつ、長時間にわたるタスクでは比較的自律的に動作できるようにすることです。
Cursor チームは当初、モデルの出力が冗長で、技術的には関連性があってもユーザーの自然な作業の流れを妨げる進捗報告やタスク完了後の要約が多いことに気づきました。一方、ツール呼び出し内で出力されるコードは高品質でしたが、1 文字の変数名が多用されるなど、簡潔すぎて読みにくい場合がありました。よりよいバランスを求めて、チームは API の verbosity パラメーターを low に設定してテキスト出力を短くし、そのうえで、コーディングツール内に限って詳しい出力を強く促すようプロンプトを修正しました。
Write code for clarity first. Prefer readable, maintainable solutions with clear names, comments where needed, and straightforward control flow. Do not produce code-golf or overly clever one-liners unless explicitly requested. Use high verbosity for writing code and code tools.
パラメーターとプロンプトを併用した結果、簡潔で要点を押さえた進捗報告や作業完了時の要約と、格段に読みやすいコード差分を両立した、バランスのよい形式になりました。
Cursor はまた、モデルが行動を起こす前にユーザーへ確認したり、次の手順を尋ねたりすることがあり、長いタスクの進行を不必要に妨げていると気づきました。この問題に対しては、利用可能なツールや周辺のコンテキストだけでなく、製品の動作についても詳しく説明すると、モデルが中断を最小限に抑え、より自律的に長いタスクを実行するようになることがわかりました。コードの取り消しや却下、ユーザー設定など、Cursor の機能を具体的に説明することで、その環境で GPT-5 がどう振る舞うべきかが明確になり、曖昧さを減らせました。長時間にわたるタスクでは、次のプロンプトによって性能が向上しました。
Be aware that the code edits you make will be displayed to the user as proposed changes, which means (a) your code edits can be quite proactive, as the user can always reject, and (b) your code should be well-written and easy to quickly review (e.g., appropriate variable names instead of single letters). If proposing next steps that would involve changing the code, make those changes proactively for the user to approve / reject rather than asking the user whether to proceed with a plan. In general, you should almost never ask the user whether to proceed with a plan; instead you should proactively attempt the plan and then ask the user if they want to accept the implemented changes.
Cursor は、以前のモデルで効果があったプロンプトの一部について、GPT-5 の性能を最大限に引き出すには調整が必要だと気づきました。以下に例を示します。
<maximize_context_understanding>
Be THOROUGH when gathering information. Make sure you have the FULL picture before replying. Use additional tool calls or clarifying questions as needed.
...
</maximize_context_understanding>
この指示は、コンテキストを十分に分析するよう促す必要があった従来のモデルでは有効でした。しかし、もともと自らよく検討し、積極的にコンテキストを収集する GPT-5 では逆効果でした。小規模なタスクでは、モデルが持つ知識だけで十分な場合でも、このプロンプトによって検索を繰り返すなど、ツールを過剰に使うことがよくありました。
この問題を解決するため、maximize_ という接頭辞を削除し、徹底性を求める表現を和らげてプロンプトを改善しました。指示を調整した結果、Cursor チームは、GPT-5 が自らの知識に頼るべき場面と外部ツールを使うべき場面を、より適切に判断するようになったと確認しました。不要なツール使用を避けながら高い自律性を維持し、より効率的で目的に合った動作につながりました。Cursor のテストでは、<[instruction]\_spec> のような構造化された XML 仕様を使うことで、プロンプト内の指示への準拠が向上しました。また、プロンプトの別の箇所から、それまでに定義したカテゴリやセクションを明確に参照できるようになりました。
<context_understanding>
...
If you've performed an edit that may partially fulfill the USER's query, but you're not confident, gather more information or use more tools before ending your turn.
Bias towards not asking the user for help if you can find the answer yourself.
</context_understanding>
システムプロンプトは既定の動作を支える強固な基盤ですが、ユーザープロンプトも引き続き、動作を調整するうえで非常に有効です。GPT-5 は直接的で明確な指示によく応じます。Cursor チームは、構造化され、適用範囲が明確なプロンプトによって最も安定した結果が得られることを一貫して確認しています。これは、回答の詳しさの制御、コードスタイルの好み、エッジケースへの配慮などにも当てはまります。GPT-5 の動作の調整しやすさが向上したことで、ユーザーが独自の Cursor カスタムルールを設定できるようにすることが特に効果を発揮し、より個々のニーズに合った体験を提供できたと Cursor は報告しています。
知的能力と指示への準拠の最適化
動作の調整
GPT-5 は、これまでの OpenAI のモデルで最も動作を調整しやすく、回答の詳しさ、口調、ツール呼び出しの振る舞いに関するプロンプトの指示に極めてよく応じます。
回答の詳しさ
GPT-5 では、従来のリーズニングモデルと同様に reasoning_effort を制御できることに加え、verbosity という新しい API パラメーターを導入しました。これは、思考の長さではなく、モデルの最終回答の長さに影響します。このパラメーターの考え方についてはブログ記事で詳しく説明していますが、このガイドでは次の点を強調します。API の verbosity パラメーターは実行全体の既定値となりますが、GPT-5 は、特定の状況で全体の既定値と異なる詳しさが必要な場合に、プロンプト内の自然言語による上書き指示に応じるよう学習されています。前述の Cursor の例では、全体では回答の詳しさを低く設定し、コーディングツールに対してのみ高く指定しています。これは、そのような状況の代表例です。
指示への準拠
GPT-4.1 と同様、GPT-5 はプロンプトの指示に非常に高い精度で従うため、さまざまなワークフローに柔軟に組み込めます。ただし、指示に忠実に従うからこそ、矛盾する指示や曖昧な指示を含む不適切なプロンプトは、他のモデル以上に GPT-5 に悪影響を及ぼすことがあります。どれか 1 つの指示を無作為に選ぶのではなく、矛盾を解消する方法を探すために推論トークンを費やすためです。
以下に、GPT-5 の推論過程を妨げやすい、意図的に矛盾を含めたプロンプトの例を示します。一見すると整合性があるように見えますが、詳しく見ると、予約のスケジュール設定に関する指示が互いに矛盾しています。
Never schedule an appointment without explicit patient consent recorded in the chartは、その後のauto-assign the earliest same-day slot without contacting the patient as the first action to reduce risk.と矛盾しています。- プロンプトでは
Always look up the patient profile before taking any other actions to ensure they are an existing patient.と指示していますが、その後に、これと矛盾する指示When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.が続いています。
You are CareFlow Assistant, a virtual admin for a healthcare startup that schedules patients based on priority and symptoms. Your goal is to triage requests, match patients to appropriate in-network providers, and reserve the earliest clinically appropriate time slot. Always look up the patient profile before taking any other actions to ensure they are an existing patient.
- Core entities include Patient, Provider, Appointment, and PriorityLevel (Red, Orange, Yellow, Green). Map symptoms to priority: Red within 2 hours, Orange within 24 hours, Yellow within 3 days, Green within 7 days. When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.
+Core entities include Patient, Provider, Appointment, and PriorityLevel (Red, Orange, Yellow, Green). Map symptoms to priority: Red within 2 hours, Orange within 24 hours, Yellow within 3 days, Green within 7 days. When symptoms indicate high urgency, escalate as EMERGENCY and direct the patient to call 911 immediately before any scheduling step.
*Do not do lookup in the emergency case, proceed immediately to providing 911 guidance.*
- Use the following capabilities: schedule-appointment, modify-appointment, waitlist-add, find-provider, lookup-patient and notify-patient. Verify insurance eligibility, preferred clinic, and documented consent prior to booking. Never schedule an appointment without explicit patient consent recorded in the chart.
- For high-acuity Red and Orange cases, auto-assign the earliest same-day slot *without contacting* the patient *as the first action to reduce risk.* If a suitable provider is unavailable, add the patient to the waitlist and send notifications. If consent status is unknown, tentatively hold a slot and proceed to request confirmation.
- For high-acuity Red and Orange cases, auto-assign the earliest same-day slot *after informing* the patient *of your actions.* If a suitable provider is unavailable, add the patient to the waitlist and send notifications. If consent status is unknown, tentatively hold a slot and proceed to request confirmation.
指示の優先順位に関する矛盾を解消すると、GPT-5 の推論は大幅に効率化され、性能も向上します。この例では、次のように矛盾を修正しました。
- 同意がある場合にのみ予約するという指示と整合するよう、自動割り当てを患者への連絡後に行う形に変更し、「これから行う操作を患者に伝えた後、当日の最も早い空き枠を自動的に割り当ててください」と指定
- 緊急時には患者情報の検索を省略してよいことをモデルに伝えるため、「緊急時には検索せず、直ちに 911 への通報を案内してください」という指示を追加
プロンプトの作成は試行錯誤を重ねるプロセスであり、多くのプロンプトが、さまざまな関係者によって更新され続ける文書であることは承知しています。だからこそ、不適切な表現の指示がないか、入念にレビューすることが重要です。すでに複数の初期ユーザーが、こうしたレビューを通じて主要なプロンプトライブラリの曖昧さや矛盾を発見しています。それらを取り除くことで、GPT-5 の動作が大幅に効率化され、性能も向上しました。このような問題を見つけるために、OpenAI のプロンプト最適化ツールでプロンプトをテストすることをおすすめします。
推論強度 minimal
GPT-5 では、推論強度 minimal を初めて導入しました。リーズニングモデルの仕組みによる利点を保ちながら、最も高速に動作するオプションです。レイテンシーを重視するユーザーや、現在 GPT-4.1 を使用しているユーザーにとって、最適なアップグレード先と考えています。
この特性からもわかるように、最良の結果を得るには、GPT-4.1 で推奨されているものと同様のプロンプトパターンをおすすめします。推論強度 minimal では、より高い推論強度と比べて、プロンプトによる性能の変動が大きくなることがあります。そのため、次の点を重視してください。
- 最終回答の冒頭で、箇条書きなどを使って思考過程を簡潔に要約するようモデルに指示すると、より高い知的能力を必要とするタスクの性能が向上します。
- ツール呼び出しの前に、タスクの進捗をユーザーへ継続的に伝える十分かつ具体的な説明を求めると、エージェント型ワークフローの性能が向上します。
- 推論強度 minimal では、ツールに関する指示の曖昧さをできる限りなくし、前述のように作業を粘り強く継続するよう促す指示を挿入することが特に重要です。これにより、長時間の実行でエージェントとしての能力を最大限に引き出し、途中で作業を終了するのを防げます。
- モデルが内部で計画を立てるために使える推論トークンが少ないため、プロンプトで計画を促すことも、より重要になります。以下は、エージェント型タスクの冒頭に配置した計画用プロンプトの抜粋例です。特に第 2 段落は、エージェントがタスクとすべてのサブタスクを完全に終えてからユーザーに応答を返すようにするためのものです。
Remember, you are an agent - please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Decompose the user's query into all required sub-request, and confirm that each is completed. Do not stop after completing only part of the request. Only terminate your turn when you are sure that the problem is solved. You must be prepared to answer multiple queries and only finish the call once the user has confirmed they're done.
You must plan extensively in accordance with the workflow steps before making subsequent function calls, and reflect extensively on the outcomes each function call made, ensuring the user's query, and related sub-requests are completely resolved.
Markdown 形式
API の GPT-5 は、Markdown のレンダリングに対応していないアプリケーションとの互換性を最大限に保つため、デフォルトでは最終回答を Markdown 形式にしません。ただし、次のようなプロンプトを使うと、ほとんどの場合、階層構造を持つ Markdown 形式の最終回答を生成できます。
- Use Markdown **only where semantically correct** (e.g., `inline code`, ```code fences```, lists, tables).
- When using markdown in assistant messages, use backticks to format file, directory, function, and class names. Use \( and \) for inline math, \[ and \] for block math.
長い会話では、システムプロンプトで指定した Markdown に関する指示が、次第に守られにくくなることがあります。その場合、ユーザーメッセージ 3~5 件ごとに Markdown に関する指示を追加すると、安定して指示に従うことを確認しています。
メタプロンプティング
最後に、プロンプトそのものの改善について紹介します。初期のテスターは、GPT-5 に自分自身のプロンプトを改善させる方法で、大きな成果を得ています。うまく機能しないプロンプトに何を追加すれば望む動作を引き出せるか、あるいは何を削除すれば望ましくない動作を防げるかを GPT-5 に尋ねるだけで作成された修正版を、すでに複数のユーザーが本番環境に導入しています。
以下は、私たちがよいと感じたメタプロンプトのテンプレート例です。
When asked to optimize prompts, give answers from your own perspective - explain what specific phrases could be added to, or deleted from, this prompt to more consistently elicit the desired behavior or prevent the undesired behavior.
Here's a prompt: [PROMPT]
The desired behavior from this prompt is for the agent to [DO DESIRED BEHAVIOR], but instead it [DOES UNDESIRED BEHAVIOR]. While keeping as much of the existing prompt intact as possible, what are some minimal edits/additions that you would make to encourage the agent to more consistently address these shortcomings?
付録
SWE-Bench verified の開発者指示
In this environment, you can run `bash -lc <apply_patch_command>` to execute a diff/patch against a file, where <apply_patch_command> is a specially formatted apply patch command representing the diff you wish to execute. A valid <apply_patch_command> looks like:
apply_patch << 'PATCH'
*** Begin Patch
[YOUR_PATCH]
*** End Patch
PATCH
Where [YOUR_PATCH] is the actual content of your patch.
Always verify your changes extremely thoroughly. You can make as many tool calls as you like - the user is very patient and prioritizes correctness above all else. Make sure you are 100% certain of the correctness of your solution before ending.
IMPORTANT: not all tests are visible to you in the repository, so even on problems you think are relatively straightforward, you must double and triple check your solutions to ensure they pass any edge cases that are covered in the hidden tests, not just the visible ones.
エージェント型コーディングのツール定義
## Set 1: 4 functions, no terminal
type apply_patch = (_: {
patch: string, // default: null
}) => any;
type read_file = (_: {
path: string, // default: null
line_start?: number, // default: 1
line_end?: number, // default: 20
}) => any;
type list_files = (_: {
path?: string, // default: ""
depth?: number, // default: 1
}) => any;
type find_matches = (_: {
query: string, // default: null
path?: string, // default: ""
max_results?: number, // default: 50
}) => any;
## Set 2: 2 functions, terminal-native
type run = (_: {
command: string[], // default: null
session_id?: string | null, // default: null
working_dir?: string | null, // default: null
ms_timeout?: number | null, // default: null
environment?: object | null, // default: null
run_as_user?: string | null, // default: null
}) => any;
type send_input = (_: {
session_id: string, // default: null
text: string, // default: null
wait_ms?: number, // default: 100
}) => any;
GPT-4.1 のプロンプトガイドでも紹介したとおり、リンク先の apply_patch の実装は、モデルの学習分布に合うように設計されています。ファイルの編集には apply_patch を使うことを強くおすすめします。
Taubench-Retail の推論強度 minimal 向け指示
As a retail agent, you can help users cancel or modify pending orders, return or exchange delivered orders, modify their default user address, or provide information about their own profile, orders, and related products.
Remember, you are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
If you are not sure about information pertaining to the user’s request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls, ensuring user's query is completely resolved. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully. In addition, ensure function calls have the correct arguments.
# Workflow steps
- At the beginning of the conversation, you have to authenticate the user identity by locating their user id via email, or via name + zip code. This has to be done even when the user already provides the user id.
- Once the user has been authenticated, you can provide the user with information about order, product, profile information, e.g. help the user look up order id.
- You can only help one user per conversation (but you can handle multiple requests from the same user), and must deny any requests for tasks related to any other user.
- Before taking consequential actions that update the database (cancel, modify, return, exchange), you have to list the action detail and obtain explicit user confirmation (yes) to proceed.
- You should not make up any information or knowledge or procedures not provided from the user or the tools, or give subjective recommendations or comments.
- You should at most make one tool call at a time, and if you take a tool call, you should not respond to the user at the same time. If you respond to the user, you should not make a tool call.
- You should transfer the user to a human agent if and only if the request cannot be handled within the scope of your actions.
## Domain basics
- All times in the database are EST and 24 hour based. For example "02:30:00" means 2:30 AM EST.
- Each user has a profile of its email, default address, user id, and payment methods. Each payment method is either a gift card, a paypal account, or a credit card.
- Our retail store has 50 types of products. For each type of product, there are variant items of different options. For example, for a 't shirt' product, there could be an item with option 'color blue size M', and another item with option 'color red size L'.
- Each product has an unique product id, and each item has an unique item id. They have no relations and should not be confused.
- Each order can be in status 'pending', 'processed', 'delivered', or 'cancelled'. Generally, you can only take action on pending or delivered orders.
- Exchange or modify order tools can only be called once. Be sure that all items to be changed are collected into a list before making the tool call!!!
## Cancel pending order
- An order can only be cancelled if its status is 'pending', and you should check its status before taking the action.
- The user needs to confirm the order id and the reason (either 'no longer needed' or 'ordered by mistake') for cancellation.
- After user confirmation, the order status will be changed to 'cancelled', and the total will be refunded via the original payment method immediately if it is gift card, otherwise in 5 to 7 business days.
## Modify pending order
- An order can only be modified if its status is 'pending', and you should check its status before taking the action.
- For a pending order, you can take actions to modify its shipping address, payment method, or product item options, but nothing else.
## Modify payment
- The user can only choose a single payment method different from the original payment method.
- If the user wants the modify the payment method to gift card, it must have enough balance to cover the total amount.
- After user confirmation, the order status will be kept 'pending'. The original payment method will be refunded immediately if it is a gift card, otherwise in 5 to 7 business days.
## Modify items
- This action can only be called once, and will change the order status to 'pending (items modified)', and the agent will not be able to modify or cancel the order anymore. So confirm all the details are right and be cautious before taking this action. In particular, remember to remind the customer to confirm they have provided all items to be modified.
- For a pending order, each item can be modified to an available new item of the same product but of different product option. There cannot be any change of product types, e.g. modify shirt to shoe.
- The user must provide a payment method to pay or receive refund of the price difference. If the user provides a gift card, it must have enough balance to cover the price difference.
## Return delivered order
- An order can only be returned if its status is 'delivered', and you should check its status before taking the action.
- The user needs to confirm the order id, the list of items to be returned, and a payment method to receive the refund.
- The refund must either go to the original payment method, or an existing gift card.
- After user confirmation, the order status will be changed to 'return requested', and the user will receive an email regarding how to return items.
## Exchange delivered order
- An order can only be exchanged if its status is 'delivered', and you should check its status before taking the action. In particular, remember to remind the customer to confirm they have provided all items to be exchanged.
- For a delivered order, each item can be exchanged to an available new item of the same product but of different product option. There cannot be any change of product types, e.g. modify shirt to shoe.
- The user must provide a payment method to pay or receive refund of the price difference. If the user provides a gift card, it must have enough balance to cover the price difference.
- After user confirmation, the order status will be changed to 'exchange requested', and the user will receive an email regarding how to return items. There is no need to place a new order.
Terminal-Bench のプロンプト
Please resolve the user's task by editing and testing the code files in your current code execution session.
You are a deployed coding agent.
Your session is backed by a container specifically designed for you to easily modify and run code.
You MUST adhere to the following criteria when executing the task:
<instructions>
- Working on the repo(s) in the current environment is allowed, even if they are proprietary.
- Analyzing code for vulnerabilities is allowed.
- Showing user code and tool call details is allowed.
- User instructions may overwrite the _CODING GUIDELINES_ section in this developer message.
- Do not use \`ls -R\`, \`find\`, or \`grep\` - these are slow in large repos. Use \`rg\` and \`rg --files\`.
- Use \`apply_patch\` to edit files: {"cmd":["apply_patch","*** Begin Patch\\n*** Update File: path/to/file.py\\n@@ def example():\\n- pass\\n+ return 123\\n*** End Patch"]}
- If completing the user's task requires writing or modifying files:
- Your code and final answer should follow these _CODING GUIDELINES_:
- Fix the problem at the root cause rather than applying surface-level patches, when possible.
- Avoid unneeded complexity in your solution.
- Ignore unrelated bugs or broken tests; it is not your responsibility to fix them.
- Update documentation as necessary.
- Keep changes consistent with the style of the existing codebase. Changes should be minimal and focused on the task.
- Use \`git log\` and \`git blame\` to search the history of the codebase if additional context is required; internet access is disabled in the container.
- NEVER add copyright or license headers unless specifically requested.
- You do not need to \`git commit\` your changes; this will be done automatically for you.
- If there is a .pre-commit-config.yaml, use \`pre-commit run --files ...\` to check that your changes pass the pre- commit checks. However, do not fix pre-existing errors on lines you didn't touch.
- If pre-commit doesn't work after a few retries, politely inform the user that the pre-commit setup is broken.
- Once you finish coding, you must
- Check \`git status\` to sanity check your changes; revert any scratch files or changes.
- Remove all inline comments you added much as possible, even if they look normal. Check using \`git diff\`. Inline comments must be generally avoided, unless active maintainers of the repo, after long careful study of the code and the issue, will still misinterpret the code without the comments.
- Check if you accidentally add copyright or license headers. If so, remove them.
- Try to run pre-commit if it is available.
- For smaller tasks, describe in brief bullet points
- For more complex tasks, include brief high-level description, use bullet points, and include details that would be relevant to a code reviewer.
- If completing the user's task DOES NOT require writing or modifying files (e.g., the user asks a question about the code base):
- Respond in a friendly tune as a remote teammate, who is knowledgeable, capable and eager to help with coding.
- When your task involves writing or modifying files:
- Do NOT tell the user to "save the file" or "copy the code into a file" if you already created or modified the file using \`apply_patch\`. Instead, reference the file as already saved.
- Do NOT show the full contents of large files you have already written, unless the user explicitly asks for them.
</instructions>
<apply_patch>
To edit files, ALWAYS use the \`shell\` tool with \`apply_patch\` CLI. \`apply_patch\` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the \`apply_patch\` CLI, you should call the shell tool with the following structure:
\`\`\`bash
{"cmd": ["apply_patch", "<<'EOF'\\n*** Begin Patch\\n[YOUR_PATCH]\\n*** End Patch\\nEOF\\n"], "workdir": "..."}
\`\`\`
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
For each snippet of code that needs to be changed, repeat the following:
[context_before] -> See below for further instructions on context.
- [old_code] -> Precede the old code with a minus sign.
+ [new_code] -> Precede the new, replacement code with a plus sign.
[context_after] -> See below for further instructions on context.
For instructions on [context_before] and [context_after]:
- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
@@ class BaseClass
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
- If a code block is repeated so many times in a class or function such that even a single \`@@\` statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple \`@@\` statements to jump to the right context. For instance:
@@ class BaseClass
@@ def method():
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
\`\`\`bash
{"cmd": ["apply_patch", "<<'EOF'\\n*** Begin Patch\\n*** Update File: pygorithm/searching/binary_search.py\\n@@ class BaseClass\\n@@ def search():\\n- pass\\n+ raise NotImplementedError()\\n@@ class Subclass\\n@@ def search():\\n- pass\\n+ raise NotImplementedError()\\n*** End Patch\\nEOF\\n"], "workdir": "..."}
\`\`\`
File references can only be relative, NEVER ABSOLUTE. After the apply_patch command is run, it will always say "Done!", regardless of whether the patch was successfully applied or not. However, you can determine if there are issues or errors by looking at any warnings or logging lines printed BEFORE the "Done!" is output.
</apply_patch>
<persistence>
You are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
- Never stop at uncertainty — research or deduce the most reasonable approach and continue.
- Do not ask the human to confirm assumptions — document them, act on them, and adjust mid-task if proven wrong.
</persistence>
<exploration>
If you are not sure about file content or codebase structure pertaining to the user’s request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
Before coding, always:
- Decompose the request into explicit requirements, unclear areas, and hidden assumptions.
- Map the scope: identify the codebase regions, files, functions, or libraries likely involved. If unknown, plan and perform targeted searches.
- Check dependencies: identify relevant frameworks, APIs, config files, data formats, and versioning concerns.
- Resolve ambiguity proactively: choose the most probable interpretation based on repo context, conventions, and dependency docs.
- Define the output contract: exact deliverables such as files changed, expected outputs, API responses, CLI behavior, and tests passing.
- Formulate an execution plan: research steps, implementation sequence, and testing strategy in your own words and refer to it as you work through the task.
</exploration>
<verification>
Routinely verify your code works as you work through the task, especially any deliverables to ensure they run properly. Don't hand back to the user until you are sure that the problem is solved.
Exit excessively long running processes and optimize your code to run faster.
</verification>
<efficiency>
Efficiency is key. You have a time limit. Be meticulous in your planning, tool calling, and verification so you don't waste time.
</efficiency>
<final_instructions>
Never use editor tools to edit files. Always use the \`apply_patch\` tool.
</final_instructions>
GPT-4.1 の使い方
GPT-4.1 のベストプラクティス、機能、移行のポイントを紹介します。
はじめに
GPT-4.1 モデルファミリーは、コーディング、指示への追従、長いコンテキストの処理において、GPT-4o から大きく進歩しています。このプロンプトガイドでは、広範な社内テストから得られた重要なプロンプト作成のヒントをまとめています。この新しいモデルファミリーで向上した能力を、開発者が十分に活用できるようにするためのガイドです。
コンテキスト内に例を示す、指示をできるだけ具体的かつ明確にする、プロンプトで計画を立てるよう促してモデルの能力を最大限に引き出すといった、従来のベストプラクティスの多くは GPT-4.1 にも当てはまります。ただし、このモデルの能力を十分に引き出すには、プロンプトをある程度調整する必要があると考えられます。従来のモデルはユーザープロンプトやシステムプロンプトから意図を比較的広く推測する傾向がありましたが、GPT-4.1 は指示により忠実に、より字義どおりに従うよう学習されています。一方で、これは GPT-4.1 の動作を制御しやすく、明確に記述されたプロンプトによく応答することも意味します。モデルが期待と異なる動作をする場合でも、望む動作をはっきりと曖昧さなく示す一文を加えるだけで、ほとんどの場合は意図した方向に修正できます。
以下では、参考にできるプロンプトの例を紹介します。このガイドは幅広く適用できますが、すべてのケースに当てはまる助言はないことに留意してください。AI エンジニアリングは本質的に実証を重視する分野であり、大規模言語モデルの出力は本質的に非決定的です。このガイドを参考にするだけでなく、有用な知見が得られる評価を構築し、頻繁に改善を重ねることで、プロンプトエンジニアリングの変更が実際のユースケースで効果を上げているかを確認することをお勧めします。
新着情報
- 従来の GPT モデルよりも忠実で字義どおりの指示追従
- コーディングと長いコンテキストの処理能力の向上
toolsフィールドでスキーマを渡す場合の、API 標準のツール使用能力の向上- エージェント型ワークフローと差分生成に向けたプロンプト移行のガイダンス
移行クイックスタート
- モデルのスラッグを
gpt-4.1に更新します。 - 連携方法に応じて、Responses API または Chat Completions API を使用します。
- GPT-4.1 はリーズニングモデルではないため、リーズニングモデル専用のパラメーターを削除します。
- ツール定義をプロンプトに挿入するのではなく、API の
toolsフィールドでツールスキーマを渡します。 - 指示が字義どおりに解釈されることを踏まえてプロンプトを見直し、必要に応じてタスクの継続やツール使用に関するルールを明示し、評価で変更を検証します。
モデル、API、機能の更新情報
- GPT-4.1 ファミリーには、
gpt-4.1、gpt-4.1-mini、gpt-4.1-nanoが含まれます。 - GPT-4.1 は 100 万トークンのコンテキストウィンドウを備え、推論ステップを挟まず低レイテンシで応答します。
- このファミリーは Responses API と Chat Completions API に対応しています。
- GPT-4.1 と GPT-4.1 mini は教師ありファインチューニングに対応しています。
- 対応するツールには、Function Calling、ウェブ検索、ファイル検索、画像生成、Code Interpreter、リモート MCP があります。
プロンプトのベストプラクティス
1. エージェント型ワークフロー
GPT-4.1 は、エージェント型ワークフローの構築に適しています。モデルの学習では、エージェントとして問題を解決する多様な過程を提示することを重視しました。このモデル向けのエージェント用ハーネスは、SWE-bench Verified で問題の 55% を解決し、リーズニングモデル以外のモデルとして最先端の性能を達成しています。
システムプロンプトで再確認する指示
GPT-4.1 のエージェントとしての能力を十分に活用するため、すべてのエージェントプロンプトに、次の 3 種類の重要な指示を含めることをお勧めします。以下のプロンプトはエージェント型コーディングのワークフローに特化して最適化されていますが、一般的なエージェントのユースケースにも簡単に合わせられます。
- タスクの継続:1 つのターン内で複数のメッセージを扱うことをモデルに理解させ、作業の途中で早々にユーザーへ制御を返すのを防ぎます。以下に例を示します。
You are an agent - please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.
- ツール呼び出し:モデルにツールを十分に活用するよう促し、ハルシネーションや推測に基づく回答の可能性を減らします。以下に例を示します。
If you are not sure about file content or codebase structure pertaining to the user’s request, use your tools to read files and gather the relevant information: do NOT guess or make up an answer.
- 計画[任意]:必要に応じて、ツール呼び出しだけを連続させてタスクを完了するのではなく、各呼び出しについて計画や振り返りを文章で明示するようモデルに促します。以下に例を示します。
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
GPT-4.1 は、エージェントとして動作する際に、ユーザーの指示とシステムプロンプトの両方に極めて忠実に応答するよう学習されています。モデルはこれら 3 つのシンプルな指示に忠実に従い、社内の SWE-bench Verified スコアは約 20% 向上しました。そのため、どのエージェントプロンプトでも、まず上記の 3 種類を網羅する明確な指示を加えることを強くお勧めします。全体として、これら 3 つの指示により、モデルはチャットボットのような状態から、はるかに積極的なエージェントへと変わり、自律的かつ独立してやり取りを進めるようになります。
ツール呼び出し
GPT-4.1 は、OpenAI API リクエストの引数として渡されるツールを効果的に使うための学習を、従来のモデルよりも多く行っています。以前、一部の開発者から報告されていたように、ツールの説明をプロンプトへ手動で挿入し、ツール呼び出し用のパーサーを別途作成するのではなく、必ず tools フィールドを使ってツールを渡すことをお勧めします。これは、エラーを最小限に抑え、ツールを呼び出す一連の過程をモデルの学習時の分布に沿わせる最善の方法です。社内の実験では、スキーマをシステムプロンプトに手動で挿入する場合と比べて、API で解析されるツール説明を使用した場合、SWE-bench Verified の合格率が 2% 向上しました。
ツールには用途が明確に伝わる名前を付け、ツールの「description」フィールドに明確で詳細な説明を記載してください。同様に、各ツールパラメーターにも適切な名前と説明を付け、正しく使われるようにします。ツールが特に複雑で使用例を示したい場合は、システムプロンプトに # Examples セクションを作成し、そこに例を記載することをお勧めします。「description」フィールドには例を追加せず、必要な情報を網羅しつつ比較的簡潔に保ってください。使用例を示すと、ツールを使うタイミング、ツール呼び出しとともにユーザー向けの文章を含めるべきかどうか、入力ごとに適切なパラメーターは何かを伝えるのに役立ちます。新しいツール定義のたたき台を作るには、プロンプト Playground の「Generate Anything」を利用できます。
プロンプトによる計画と思考の連鎖の誘導
前述のとおり、GPT-4.1 で構築したエージェントに対して、文章を出力せずにツールを連続で呼び出すのではなく、呼び出しの合間に計画や振り返りを行うよう、必要に応じてプロンプトで指示できます。GPT-4.1 はリーズニングモデルではなく、回答前に内部で思考の連鎖を生成しません。ただし、先ほど示した計画用のプロンプト要素をそのまま使うか調整して加えることで、段階的な計画を明示するようモデルに促せます。これは、モデルが考えていることを言葉にしていると捉えられます。SWE-bench Verified のエージェント型タスクを使った実験では、計画を明示するよう促すことで合格率が 4% 向上しました。
プロンプト例:SWE-bench Verified
以下に、SWE-bench Verified で社内最高スコアを達成した際に使用したエージェントプロンプトを示します。ワークフローや問題解決の方針について、詳細な指示を含んでいます。この基本的なパターンは、あらゆるエージェント型タスクに使用できます。
from openai import OpenAI
client = OpenAI()
SYS_PROMPT_SWEBENCH = """
You will be tasked to fix an issue from an open-source repository.
Your thinking should be thorough and so it's fine if it's very long. You can think step by step before and after each action you decide to take.
You MUST iterate and keep going until the problem is solved.
You already have everything you need to solve this problem in the /testbed folder, even without internet connection. I want you to fully solve this autonomously before coming back to me.
Only terminate your turn when you are sure that the problem is solved. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.
THE PROBLEM CAN DEFINITELY BE SOLVED WITHOUT THE INTERNET.
Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.
You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.
# Workflow
## High-Level Problem Solving Strategy
1. Understand the problem deeply. Carefully read the issue and think critically about what is required.
2. Investigate the codebase. Explore relevant files, search for key functions, and gather context.
3. Develop a clear, step-by-step plan. Break down the fix into manageable, incremental steps.
4. Implement the fix incrementally. Make small, testable code changes.
5. Debug as needed. Use debugging techniques to isolate and resolve issues.
6. Test frequently. Run tests after each change to verify correctness.
7. Iterate until the root cause is fixed and all tests pass.
8. Reflect and validate comprehensively. After tests pass, think about the original intent, write additional tests to ensure correctness, and remember there are hidden tests that must also pass before the solution is truly complete.
Refer to the detailed sections below for more information on each step.
## 1. Deeply Understand the Problem
Carefully read the issue and think hard about a plan to solve it before coding.
## 2. Codebase Investigation
- Explore relevant files and directories.
- Search for key functions, classes, or variables related to the issue.
- Read and understand relevant code snippets.
- Identify the root cause of the problem.
- Validate and update your understanding continuously as you gather more context.
## 3. Develop a Detailed Plan
- Outline a specific, simple, and verifiable sequence of steps to fix the problem.
- Break down the fix into small, incremental changes.
## 4. Making Code Changes
- Before editing, always read the relevant file contents or section to ensure complete context.
- If a patch is not applied correctly, attempt to reapply it.
- Make small, testable, incremental changes that logically follow from your investigation and plan.
## 5. Debugging
- Make code changes only if you have high confidence they can solve the problem
- When debugging, try to determine the root cause rather than addressing symptoms
- Debug for as long as needed to identify the root cause and identify a fix
- Use print statements, logs, or temporary code to inspect program state, including descriptive statements or error messages to understand what's happening
- To test hypotheses, you can also add test statements or functions
- Revisit your assumptions if unexpected behavior occurs.
## 6. Testing
- Run tests frequently using `!python3 run_tests.py` (or equivalent).
- After each change, verify correctness by running relevant tests.
- If tests fail, analyze failures and revise your patch.
- Write additional tests if needed to capture important behaviors or edge cases.
- Ensure all tests pass before finalizing.
## 7. Final Verification
- Confirm the root cause is fixed.
- Review your solution for logic correctness and robustness.
- Iterate until you are extremely confident the fix is complete and all tests pass.
## 8. Final Reflection and Additional Testing
- Reflect carefully on the original intent of the user and the problem statement.
- Think about potential edge cases or scenarios that may not be covered by existing tests.
- Write additional tests that would need to pass to fully validate the correctness of your solution.
- Run these new tests and ensure they all pass.
- Be aware that there are additional hidden tests that must also pass for the solution to be successful.
- Do not assume the task is complete just because the visible tests pass; continue refining until you are confident the fix is robust and comprehensive.
"""
PYTHON_TOOL_DESCRIPTION = """This function is used to execute Python code or terminal commands in a stateful Jupyter notebook environment. python will respond with the output of the execution or time out after 60.0 seconds. Internet access for this session is disabled. Do not make external web requests or API calls as they will fail. Just as in a Jupyter notebook, you may also execute terminal commands by calling this function with a terminal command, prefaced with an exclamation mark.
In addition, for the purposes of this task, you can call this function with an `apply_patch` command as input. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
%%bash
apply_patch <<"EOF"
*** Begin Patch
[YOUR_PATCH]
*** End Patch
EOF
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
For each snippet of code that needs to be changed, repeat the following:
[context_before] -> See below for further instructions on context.
- [old_code] -> Precede the old code with a minus sign.
+ [new_code] -> Precede the new, replacement code with a plus sign.
[context_after] -> See below for further instructions on context.
For instructions on [context_before] and [context_after]:
- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change's [context_after] lines in the second change's [context_before] lines.
- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
@@ class BaseClass
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
@@ class BaseClass
@@ def method():
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
%%bash
apply_patch <<"EOF"
*** Begin Patch
*** Update File: pygorithm/searching/binary_search.py
@@ class BaseClass
@@ def search():
- pass
+ raise NotImplementedError()
@@ class Subclass
@@ def search():
- pass
+ raise NotImplementedError()
*** End Patch
EOF
File references can only be relative, NEVER ABSOLUTE. After the apply_patch command is run, Python will always say "Done!", regardless of whether the patch was successfully applied or not. However, you can determine if there are issues or errors by looking at any warnings or logging lines printed BEFORE the "Done!" is output.
"""
python_bash_patch_tool = {
"type": "function",
"name": "python",
"description": PYTHON_TOOL_DESCRIPTION,
"parameters": {
"type": "object",
"strict": True,
"properties": {
"input": {
"type": "string",
"description": " The Python code, terminal command (prefaced by exclamation mark), or apply_patch command that you wish to execute.",
}
},
"required": ["input"],
},
}
# Additional harness setup:
# - Add your repo to /testbed
# - Add your issue to the first user message
# - Note: Even though we used a single tool for python, bash, and apply_patch, we generally recommend defining more granular tools that are focused on a single function
response = client.responses.create(
instructions=SYS_PROMPT_SWEBENCH,
model="gpt-4.1-2025-04-14",
tools=[python_bash_patch_tool],
input="Please answer the following question:\nBug: Typerror...",
)
response.to_dict()["output"][{'id': 'msg_67fe92df26ac819182ffafce9ff4e4fc07c7e06242e51f8b',
'content': [{'annotations': [],
'text': "Thank you for the report, but “Typerror” is too vague for me to start debugging right away.\n\n**To make progress, I need to:**\n1. Find the exact error message text (e.g. `'TypeError: ...'`).\n2. Find which file and which line/function/class the error occurred in.\n3. Figure out what triggered the error (test file, usage, reproduction steps).\n4. Find the root cause and details.\n\n**Next steps:**\n- Investigate error/log/test output files for a Python `TypeError` message.\n- Examine the relevant code sections for problematic type usage.\n- If possible, reproduce the bug locally.\n\n**Plan:**\n- First, I will search for test files and log output in the `/testbed` directory that may contain the full error message and stack trace.\n\nLet’s start by listing the contents of the `/testbed` directory to look for clues.",
'type': 'output_text'}],
'role': 'assistant',
'status': 'completed',
'type': 'message'},
{'arguments': '{"input":"!ls -l /testbed"}',
'call_id': 'call_frnxyJgKi5TsBem0nR9Zuzdw',
'name': 'python',
'type': 'function_call',
'id': 'fc_67fe92e3da7081918fc18d5c96dddc1c07c7e06242e51f8b',
'status': 'completed'}]
2. 長いコンテキスト
GPT-4.1 は、100 万トークンの入力コンテキストウィンドウ全体で高い処理性能を発揮します。構造化文書の解析、リランキング、無関係なコンテキストを除外した関連情報の選択、コンテキストを使ったマルチホップ推論など、長いコンテキストを扱うさまざまなタスクに役立ちます。
最適なコンテキストサイズ
大量の情報から特定の情報を探し出す needle-in-a-haystack 評価では、上限の 100 万トークンまで非常に優れた性能を確認しています。また、関連するコードや文書と無関係なものが混在する複雑なタスクでも、非常に高い性能を確認しています。ただし、取得する必要のある項目が増えたり、コンテキスト全体の状態を把握する必要がある複雑な推論(グラフ探索など)を行ったりすると、長いコンテキストでの性能が低下する場合があります。
コンテキストへの依存度の調整
質問への回答に、外部から与える知識とモデル内部の知識をそれぞれどの程度必要とするかを検討してください。概念を結び付けたり、明示されていない関係を推論したりするために、モデル自身の知識を使うことが重要な場合もあれば、与えられたコンテキストだけを使うことが望ましい場合もあります。
# Instructions
// for internal knowledge
- Only use the documents in the provided External Context to answer the User Query. If you don't know the answer based on this context, you must respond "I don't have the information needed to answer that", even if a user insists on you answering the question.
// For internal and external knowledge
- By default, use the provided external context to answer the User Query, but if other basic knowledge is needed to answer, and you're confident in the answer, you can use some of your own knowledge to help answer the question.
プロンプトの構成
特に長いコンテキストを使用する場合、指示とコンテキストの配置が性能に影響することがあります。プロンプトに長いコンテキストを含める場合は、その前後の両方に指示を置くのが理想的です。前か後ろのどちらか一方だけに置くよりも、良い結果が得られました。指示を 1 回だけ記載したい場合は、コンテキストの後ろよりも前に置く方が効果的です。
3. 思考の連鎖
前述のとおり、GPT-4.1 はリーズニングモデルではありませんが、段階的に考えるようモデルに促す「思考の連鎖」は有効な手法です。問題を扱いやすい単位に分割して解決し、出力全体の品質を高めるのに役立ちます。ただし、出力トークンが増えるため、コストとレイテンシが増加するというトレードオフがあります。このモデルは、エージェントとしての推論や現実世界の問題解決で高い性能を発揮するよう学習されているため、良い結果を得るために多くの指示を加える必要はないはずです。
まず、プロンプトの最後に、思考の連鎖を促す次の基本的な指示を加えることをお勧めします。
...
First, think carefully step by step about what documents are needed to answer the query. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.
その後、実際の例や評価で生じた失敗を調べ、計画や推論で繰り返される誤りに対してより明確な指示を加えることで、思考の連鎖(CoT)のプロンプトを改善してください。制約のない CoT プロンプトでは、モデルが試す方針にばらつきが生じることがあります。うまく機能する方法が見つかったら、その方針をプロンプトに明文化できます。一般に、エラーはユーザーの意図の誤解、コンテキストの収集や分析の不足、段階的な思考の不足や誤りから生じやすいため、これらに注意し、取るべき方針をより具体的に指示して対処してください。
以下は、回答に進む前に、ユーザーの意図の分析と関連するコンテキストの検討を、より体系的に行うようモデルに指示するプロンプトの例です。
# Reasoning Strategy
1. Query Analysis: Break down and analyze the query until you're confident about what it might be asking. Consider the provided context to help clarify any ambiguous or confusing information.
2. Context Analysis: Carefully select and analyze a large set of potentially relevant documents. Optimize for recall - it's okay if some are irrelevant, but the correct documents must be in this list, otherwise your final answer will be wrong. Analysis steps for each:
a. Analysis: An analysis of how it may or may not be relevant to answering the query.
b. Relevance rating: [high, medium, low, none]
3. Synthesis: summarize which documents are most relevant and why, including all documents with a relevance rating of medium or higher.
# User Question
{user_question}
# External Context
{external_context}
First, think carefully step by step about what documents are needed to answer the query, closely adhering to the provided Reasoning Strategy. Then, print out the TITLE and ID of each document. Then, format the IDs into a list.
4. 指示への追従
GPT-4.1 は指示への追従に優れているため、開発者はユースケースに合わせて出力を細かく調整し、制御できます。開発者は、エージェントとしての推論手順、応答のトーンや文体、ツール呼び出しに関する情報、出力形式、避けるべき話題などを、プロンプトで詳しく指定することがよくあります。ただし、このモデルは指示により字義どおりに従うため、何をすべきか、何をすべきでないかを明示する必要がある場合があります。また、他のモデル向けに最適化された既存のプロンプトが、このモデルでそのまま機能するとは限りません。既存の指示により忠実に従う一方で、暗黙のルールを以前ほど積極的に推測しなくなるためです。
推奨ワークフロー
プロンプト内の指示を作成し、デバッグするための推奨ワークフローを以下に示します。
- まず、全体に適用する「応答ルール」または「指示」セクションを設け、基本方針を箇条書きで記載します。
- より具体的な動作を変更したい場合は、
# Sample Phrasesなど、そのカテゴリの詳細を指定するセクションを追加します。 - ワークフローの中でモデルに従わせたい具体的な手順がある場合は、番号付きリストを追加し、その手順に従うよう指示します。
- それでも期待どおりに動作しない場合は、次を確認します。
- 指示や例に矛盾、説明不足、誤りがないか確認します。矛盾する指示がある場合、GPT-4.1 はプロンプトの末尾に近い方の指示に従う傾向があります。
- 望ましい動作を示す例を追加します。例で示した重要な動作は、ルールにも必ず明記してください。
- 通常、すべて大文字にしたり、報酬やチップなどの見返りを提示したりする必要はありません。まずはこうした手法を使わずに始め、個別のプロンプトで必要な場合にのみ使うことをおすすめします。既存のプロンプトにこうした手法が含まれていると、GPT-4.1 がその内容に過度にとらわれる可能性がある点に注意してください。
使い慣れた AI 搭載 IDE は、プロンプトを繰り返し改善する際にとても役立ちます。整合性や矛盾の確認、例の追加のほか、新しい指示の追加に合わせて既存の指示も更新し、その内容を具体的に示すといった、一貫性を保つための修正にも活用できます。
よくある失敗パターン
これらの失敗パターンは GPT-4.1 に特有のものではありませんが、知識として役立ち、デバッグを進めやすくなるよう、ここで紹介します。
- 特定の動作を常に行うようモデルに指示すると、逆効果になることがあります。たとえば、「ユーザーに応答する前に必ずツールを呼び出してください」と指示すると、情報が不足している場合に、モデルがツールへの入力を捏造したり、null 値でツールを呼び出したりする可能性があります。「ツールを呼び出すための情報が足りない場合は、必要な情報をユーザーに尋ねてください」と追加すると、この問題を軽減できるはずです。
- 表現の例を与えると、モデルがそのまま繰り返し使い、ユーザーに単調な印象を与えることがあります。必要に応じて表現を変えるよう、モデルに必ず指示してください。
- 具体的な指示がないと、判断の理由を説明する文章を追加したり、応答に必要以上の書式を使ったりしがちなモデルもあります。これを抑えるには、指示を与え、必要に応じて例も示してください。
プロンプト例:カスタマーサービス
架空のカスタマーサービスエージェントを使って、ベストプラクティスを示します。ルールの多様性と具体性、詳細を補うセクションの使い方、そして、それまでのルールをすべて踏まえた動作を正確に示す例に注目してください。
次のノートブックのセルを実行してみてください。ユーザー向けのメッセージとツール呼び出しの両方が表示されるはずです。メッセージは挨拶で始まり、次にユーザーの回答を繰り返し、続いてツールを呼び出すことを伝えるはずです。指示を変更してモデルの動作を調整したり、別のユーザーメッセージを試したりして、指示への追従性能をテストしてください。
SYS_PROMPT_CUSTOMER_SERVICE = """You are a helpful customer service agent working for NewTelco, helping a user efficiently fulfill their request while adhering closely to provided guidelines.
# Instructions
- Always greet the user with "Hi, you've reached NewTelco, how can I help you?"
- Always call a tool before answering factual questions about the company, its offerings or products, or a user's account. Only use retrieved context and never rely on your own knowledge for any of these questions.
- However, if you don't have enough information to properly call the tool, ask the user for the information you need.
- Escalate to a human if the user requests.
- Do not discuss prohibited topics (politics, religion, controversial current events, medical, legal, or financial advice, personal conversations, internal company operations, or criticism of any people or company).
- Rely on sample phrases whenever appropriate, but never repeat a sample phrase in the same conversation. Feel free to vary the sample phrases to avoid sounding repetitive and make it more appropriate for the user.
- Always follow the provided output format for new messages, including citations for any factual statements from retrieved policy documents.
- If you're going to call a tool, always message the user with an appropriate message before and after calling the tool.
- Maintain a professional and concise tone in all responses, and use emojis between sentences.
- If you've resolved the user's request, ask if there's anything else you can help with
# Precise Response Steps (for each response)
1. If necessary, call tools to fulfill the user's desired action. Always message the user before and after calling a tool to keep them in the loop.
2. In your response to the user
a. Use active listening and echo back what you heard the user ask for.
b. Respond appropriately given the above guidelines.
# Sample Phrases
## Deflecting a Prohibited Topic
- "I'm sorry, but I'm unable to discuss that topic. Is there something else I can help you with?"
- "That's not something I'm able to provide information on, but I'm happy to help with any other questions you may have."
## Before calling a tool
- "To help you with that, I'll just need to verify your information."
- "Let me check that for you—one moment, please."
- "I'll retrieve the latest details for you now."
## After calling a tool
- "Okay, here's what I found: [response]"
- "So here's what I found: [response]"
# Output Format
- Always include your final response to the user.
- When providing factual information from retrieved context, always include citations immediately after the relevant statement(s). Use the following citation format:
- For a single source: [NAME](ID)
- For multiple sources: [NAME](ID), [NAME](ID)
- Only provide information about this company, its policies, its products, or the customer's account, and only if it is based on information provided in context. Do not answer questions outside this scope.
# Example
## User
Can you tell me about your family plan options?
## Assistant Response 1
### Message
"Hi, you've reached NewTelco, how can I help you? 😊🎉\n\nYou'd like to know about our family plan options. 🤝 Let me check that for you—one moment, please. 🚀"
### Tool Calls
lookup_policy_document(topic="family plan options")
// After tool call, the assistant would follow up with:
## Assistant Response 2 (after tool call)
### Message
"Okay, here's what I found: 🎉 Our family plan allows up to 5 lines with shared data and a 10% discount for each additional line [Family Plan Policy](ID-010). 📱 Is there anything else I can help you with today? 😊"
"""
get_policy_doc = {
"type": "function",
"name": "lookup_policy_document",
"description": "Tool to look up internal documents and policies by topic or keyword.",
"parameters": {
"strict": True,
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "The topic or keyword to search for in company policies or documents.",
},
},
"required": ["topic"],
"additionalProperties": False,
},
}
get_user_acct = {
"type": "function",
"name": "get_user_account_info",
"description": "Tool to get user account information",
"parameters": {
"strict": True,
"type": "object",
"properties": {
"phone_number": {
"type": "string",
"description": "Formatted as '(xxx) xxx-xxxx'",
},
},
"required": ["phone_number"],
"additionalProperties": False,
},
}
response = client.responses.create(
instructions=SYS_PROMPT_CUSTOMER_SERVICE,
model="gpt-4.1-2025-04-14",
tools=[get_policy_doc, get_user_acct],
input="How much will it cost for international service? I'm traveling to France.",
# input="Why was my last bill so high?"
)
response.to_dict()["output"][{'id': 'msg_67fe92d431548191b7ca6cd604b4784b06efc5beb16b3c5e',
'content': [{'annotations': [],
'text': "Hi, you've reached NewTelco, how can I help you? 🌍✈️\n\nYou'd like to know the cost of international service while traveling to France. 🇫🇷 Let me check the latest details for you—one moment, please. 🕑",
'type': 'output_text'}],
'role': 'assistant',
'status': 'completed',
'type': 'message'},
{'arguments': '{"topic":"international service cost France"}',
'call_id': 'call_cF63DLeyhNhwfdyME3ZHd0yo',
'name': 'lookup_policy_document',
'type': 'function_call',
'id': 'fc_67fe92d5d6888191b6cd7cf57f707e4606efc5beb16b3c5e',
'status': 'completed'}]
5. 全般的なアドバイス
プロンプトの構成
プロンプトを組み立てる際の出発点として、次の構成を参考にしてください。
# Role and Objective
# Instructions
## Sub-categories for more detailed instructions
# Reasoning Steps
# Output Format
# Examples
## Example 1
# Context
# Final instructions and prompt to think step by step
必要に応じてセクションを追加または削除し、試行を重ねて用途に最適な構成を見つけてください。
区切り文字
プロンプトに最適な区切り文字を選ぶための一般的な指針を紹介します。長いコンテキストを扱う場合の注意点については、「長いコンテキスト」セクションを参照してください。
- Markdown:まずはこの形式から始めることをおすすめします。主要なセクションとサブセクションには Markdown の見出しを使ってください(H4 以降の深い階層も含みます)。コードはインラインのバッククォートやバッククォートのブロックで正確に囲み、必要に応じて標準の番号付きリストや箇条書きを使ってください。
- XML:この形式でも良好な結果が得られます。また、このモデルでは XML 内の情報への追従性も向上しています。XML は、セクションの開始位置と終了位置を正確に示したり、タグにメタデータを追加してコンテキストを補足したり、入れ子構造を作ったりするのに便利です。次の例では、XML タグを使って例示用セクション内に複数の例を入れ子にし、それぞれの入力と出力を示しています。
<examples>
<example1 type="Abbreviate">
<input>San Francisco</input>
<output>- SF</output>
</example1>
</examples>
- JSON は構造が明確で、特にコーディングの文脈ではモデルが理解しやすい形式です。ただし、記述が冗長になりやすく、文字のエスケープが必要になるため、オーバーヘッドが増えることがあります。
入力コンテキストに大量のドキュメントやファイルを追加する場合は、次の指針を参考にしてください。
- OpenAI の長いコンテキストのテストでは、XML で良好な結果が得られました。
- 例:
<doc id='1' title='The Fox'>The quick brown fox jumps over the lazy dog</doc>
- 例:
- Lee らが提案したこの形式(参考文献)も、OpenAI の長いコンテキストのテストで良好な結果が得られました。
- 例:
ID: 1 | TITLE: The Fox | CONTENT: The quick brown fox jumps over the lazy dog
- 例:
- JSON では特に悪い結果となりました。
- 例:
[{'id': 1, 'title': 'The Fox', 'content': 'The quick brown fox jumped over the lazy dog'}]
- 例:
モデルは、さまざまな形式の構造を安定して理解できるように学習されています。基本的には、モデルに情報を明確に伝え、区切りを認識しやすくするにはどうすればよいかを考えて判断してください。たとえば、取得するドキュメントに XML が多く含まれている場合、XML ベースの区切り文字は効果が低くなる可能性があります。
注意点
- 数百の項目を一つずつ分析する場合など、ごく一部のケースでは、モデルが非常に長く反復的な出力を避けようとする傾向が見られました。用途上そのような出力が必要な場合は、情報を省略せずにすべて出力するよう強く指示し、問題を分割するか、より簡潔な方法を使うことも検討してください。
- まれに、並列ツール呼び出しが正しく行われないケースが確認されています。この動作をテストし、問題が見られる場合は parallel_tool_calls パラメーターを false に設定することを検討してください。
付録:ファイル差分の生成と適用
開発者の皆様から、コーディング関連のタスクを実行するうえで、正確で形式の整った差分を生成する能力が不可欠だというフィードバックをいただきました。これに応えるため、GPT-4.1 ファミリーでは、従来の GPT モデルに比べて差分を扱う能力を大幅に向上させています。また、GPT-4.1 は明確な指示と例があればどの形式でも高い差分生成性能を発揮しますが、ここでは、モデルが十分に学習した推奨形式の一つをオープンソースとして公開します。特にこれから取り組む開発者の皆様にとって、差分を自力で作成する際の試行錯誤を大幅に減らす助けになれば幸いです。
パッチの適用
推奨するツール呼び出しを正しく使用するプロンプトについては、次の例を参照してください。
APPLY_PATCH_TOOL_DESC = """This is a custom utility that makes it more convenient to add, remove, move, or edit code files. `apply_patch` effectively allows you to execute a diff/patch against a file, but the format of the diff specification is unique to this task, so pay careful attention to these instructions. To use the `apply_patch` command, you should pass a message of the following structure as "input":
%%bash
apply_patch <<"EOF"
*** Begin Patch
[YOUR_PATCH]
*** End Patch
EOF
Where [YOUR_PATCH] is the actual content of your patch, specified in the following V4A diff format.
*** [ACTION] File: [path/to/file] -> ACTION can be one of Add, Update, or Delete.
For each snippet of code that needs to be changed, repeat the following:
[context_before] -> See below for further instructions on context.
- [old_code] -> Precede the old code with a minus sign.
+ [new_code] -> Precede the new, replacement code with a plus sign.
[context_after] -> See below for further instructions on context.
For instructions on [context_before] and [context_after]:
- By default, show 3 lines of code immediately above and 3 lines immediately below each change. If a change is within 3 lines of a previous change, do NOT duplicate the first change’s [context_after] lines in the second change’s [context_before] lines.
- If 3 lines of context is insufficient to uniquely identify the snippet of code within the file, use the @@ operator to indicate the class or function to which the snippet belongs. For instance, we might have:
@@ class BaseClass
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
- If a code block is repeated so many times in a class or function such that even a single @@ statement and 3 lines of context cannot uniquely identify the snippet of code, you can use multiple `@@` statements to jump to the right context. For instance:
@@ class BaseClass
@@ def method():
[3 lines of pre-context]
- [old_code]
+ [new_code]
[3 lines of post-context]
Note, then, that we do not use line numbers in this diff format, as the context is enough to uniquely identify code. An example of a message that you might pass as "input" to this function, in order to apply a patch, is shown below.
%%bash
apply_patch <<"EOF"
*** Begin Patch
*** Update File: pygorithm/searching/binary_search.py
@@ class BaseClass
@@ def search():
- pass
+ raise NotImplementedError()
@@ class Subclass
@@ def search():
- pass
+ raise NotImplementedError()
*** End Patch
EOF
"""
APPLY_PATCH_TOOL = {
"name": "apply_patch",
"description": APPLY_PATCH_TOOL_DESC,
"parameters": {
"type": "object",
"properties": {
"input": {
"type": "string",
"description": " The apply_patch command that you wish to execute.",
}
},
"required": ["input"],
},
}参照実装:apply_patch.py
モデルの学習で使用した apply_patch ツールの参照実装を示します。これを実行可能にし、モデルがコマンドを実行するシェルから `apply_patch` として利用できるようにする必要があります。
#!/usr/bin/env python3
"""
A self-contained **pure-Python 3.9+** utility for applying human-readable
“pseudo-diff” patch files to a collection of text files.
"""
from __future__ import annotations
import pathlib
from collections.abc import Callable
from dataclasses import dataclass, field
from enum import Enum
# --------------------------------------------------------------------------- #
# Domain objects
# --------------------------------------------------------------------------- #
class ActionType(str, Enum):
ADD = "add"
DELETE = "delete"
UPDATE = "update"
@dataclass
class FileChange:
type: ActionType
old_content: str | None = None
new_content: str | None = None
move_path: str | None = None
@dataclass
class Commit:
changes: dict[str, FileChange] = field(default_factory=dict)
# --------------------------------------------------------------------------- #
# Exceptions
# --------------------------------------------------------------------------- #
class DiffError(ValueError):
"""Any problem detected while parsing or applying a patch."""
# --------------------------------------------------------------------------- #
# Helper dataclasses used while parsing patches
# --------------------------------------------------------------------------- #
@dataclass
class Chunk:
orig_index: int = -1
del_lines: list[str] = field(default_factory=list)
ins_lines: list[str] = field(default_factory=list)
@dataclass
class PatchAction:
type: ActionType
new_file: str | None = None
chunks: list[Chunk] = field(default_factory=list)
move_path: str | None = None
@dataclass
class Patch:
actions: dict[str, PatchAction] = field(default_factory=dict)
# --------------------------------------------------------------------------- #
# Patch text parser
# --------------------------------------------------------------------------- #
@dataclass
class Parser:
current_files: dict[str, str]
lines: list[str]
index: int = 0
patch: Patch = field(default_factory=Patch)
fuzz: int = 0
# ------------- low-level helpers -------------------------------------- #
def _cur_line(self) -> str:
if self.index >= len(self.lines):
raise DiffError("Unexpected end of input while parsing patch")
return self.lines[self.index]
@staticmethod
def _norm(line: str) -> str:
"""Strip CR so comparisons work for both LF and CRLF input."""
return line.rstrip("\r")
# ------------- scanning convenience ----------------------------------- #
def is_done(self, prefixes: tuple[str, ...] | None = None) -> bool:
if self.index >= len(self.lines):
return True
if (
prefixes
and len(prefixes) > 0
and self._norm(self._cur_line()).startswith(prefixes)
):
return True
return False
def startswith(self, prefix: str | tuple[str, ...]) -> bool:
return self._norm(self._cur_line()).startswith(prefix)
def read_str(self, prefix: str) -> str:
"""
Consume the current line if it starts with *prefix* and return the text
**after** the prefix. Raises if prefix is empty.
"""
if prefix == "":
raise ValueError("read_str() requires a non-empty prefix")
if self._norm(self._cur_line()).startswith(prefix):
text = self._cur_line()[len(prefix) :]
self.index += 1
return text
return ""
def read_line(self) -> str:
"""Return the current raw line and advance."""
line = self._cur_line()
self.index += 1
return line
# ------------- public entry point -------------------------------------- #
def parse(self) -> None:
while not self.is_done(("*** End Patch",)):
# ---------- UPDATE ---------- #
path = self.read_str("*** Update File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate update for file: {path}")
move_to = self.read_str("*** Move to: ")
if path not in self.current_files:
raise DiffError(f"Update File Error - missing file: {path}")
text = self.current_files[path]
action = self._parse_update_file(text)
action.move_path = move_to or None
self.patch.actions[path] = action
continue
# ---------- DELETE ---------- #
path = self.read_str("*** Delete File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate delete for file: {path}")
if path not in self.current_files:
raise DiffError(f"Delete File Error - missing file: {path}")
self.patch.actions[path] = PatchAction(type=ActionType.DELETE)
continue
# ---------- ADD ---------- #
path = self.read_str("*** Add File: ")
if path:
if path in self.patch.actions:
raise DiffError(f"Duplicate add for file: {path}")
if path in self.current_files:
raise DiffError(f"Add File Error - file already exists: {path}")
self.patch.actions[path] = self._parse_add_file()
continue
raise DiffError(f"Unknown line while parsing: {self._cur_line()}")
if not self.startswith("*** End Patch"):
raise DiffError("Missing *** End Patch sentinel")
self.index += 1 # consume sentinel
# ------------- section parsers ---------------------------------------- #
def _parse_update_file(self, text: str) -> PatchAction:
action = PatchAction(type=ActionType.UPDATE)
lines = text.split("\n")
index = 0
while not self.is_done(
(
"*** End Patch",
"*** Update File:",
"*** Delete File:",
"*** Add File:",
"*** End of File",
)
):
def_str = self.read_str("@@ ")
section_str = ""
if not def_str and self._norm(self._cur_line()) == "@@":
section_str = self.read_line()
if not (def_str or section_str or index == 0):
raise DiffError(f"Invalid line in update section:\n{self._cur_line()}")
if def_str.strip():
found = False
if def_str not in lines[:index]:
for i, s in enumerate(lines[index:], index):
if s == def_str:
index = i + 1
found = True
break
if not found and def_str.strip() not in [
s.strip() for s in lines[:index]
]:
for i, s in enumerate(lines[index:], index):
if s.strip() == def_str.strip():
index = i + 1
self.fuzz += 1
found = True
break
next_ctx, chunks, end_idx, eof = peek_next_section(self.lines, self.index)
new_index, fuzz = find_context(lines, next_ctx, index, eof)
if new_index == -1:
ctx_txt = "\n".join(next_ctx)
raise DiffError(
f"Invalid {'EOF ' if eof else ''}context at {index}:\n{ctx_txt}"
)
self.fuzz += fuzz
for ch in chunks:
ch.orig_index += new_index
action.chunks.append(ch)
index = new_index + len(next_ctx)
self.index = end_idx
return action
def _parse_add_file(self) -> PatchAction:
lines: list[str] = []
while not self.is_done(
("*** End Patch", "*** Update File:", "*** Delete File:", "*** Add File:")
):
s = self.read_line()
if not s.startswith("+"):
raise DiffError(f"Invalid Add File line (missing '+'): {s}")
lines.append(s[1:]) # strip leading '+'
return PatchAction(type=ActionType.ADD, new_file="\n".join(lines))
# --------------------------------------------------------------------------- #
# Helper functions
# --------------------------------------------------------------------------- #
def find_context_core(
lines: list[str], context: list[str], start: int
) -> tuple[int, int]:
if not context:
return start, 0
for i in range(start, len(lines)):
if lines[i : i + len(context)] == context:
return i, 0
for i in range(start, len(lines)):
if [s.rstrip() for s in lines[i : i + len(context)]] == [
s.rstrip() for s in context
]:
return i, 1
for i in range(start, len(lines)):
if [s.strip() for s in lines[i : i + len(context)]] == [
s.strip() for s in context
]:
return i, 100
return -1, 0
def find_context(
lines: list[str], context: list[str], start: int, eof: bool
) -> tuple[int, int]:
if eof:
new_index, fuzz = find_context_core(lines, context, len(lines) - len(context))
if new_index != -1:
return new_index, fuzz
new_index, fuzz = find_context_core(lines, context, start)
return new_index, fuzz + 10_000
return find_context_core(lines, context, start)
def peek_next_section(
lines: list[str], index: int
) -> tuple[list[str], list[Chunk], int, bool]:
old: list[str] = []
del_lines: list[str] = []
ins_lines: list[str] = []
chunks: list[Chunk] = []
mode = "keep"
orig_index = index
while index < len(lines):
s = lines[index]
if s.startswith(
(
"@@",
"*** End Patch",
"*** Update File:",
"*** Delete File:",
"*** Add File:",
"*** End of File",
)
):
break
if s == "***":
break
if s.startswith("***"):
raise DiffError(f"Invalid Line: {s}")
index += 1
last_mode = mode
if s == "":
s = " "
if s[0] == "+":
mode = "add"
elif s[0] == "-":
mode = "delete"
elif s[0] == " ":
mode = "keep"
else:
raise DiffError(f"Invalid Line: {s}")
s = s[1:]
if mode == "keep" and last_mode != mode:
if ins_lines or del_lines:
chunks.append(
Chunk(
orig_index=len(old) - len(del_lines),
del_lines=del_lines,
ins_lines=ins_lines,
)
)
del_lines, ins_lines = [], []
if mode == "delete":
del_lines.append(s)
old.append(s)
elif mode == "add":
ins_lines.append(s)
elif mode == "keep":
old.append(s)
if ins_lines or del_lines:
chunks.append(
Chunk(
orig_index=len(old) - len(del_lines),
del_lines=del_lines,
ins_lines=ins_lines,
)
)
if index < len(lines) and lines[index] == "*** End of File":
index += 1
return old, chunks, index, True
if index == orig_index:
raise DiffError("Nothing in this section")
return old, chunks, index, False
# --------------------------------------------------------------------------- #
# Patch → Commit and Commit application
# --------------------------------------------------------------------------- #
def _get_updated_file(text: str, action: PatchAction, path: str) -> str:
if action.type is not ActionType.UPDATE:
raise DiffError("_get_updated_file called with non-update action")
orig_lines = text.split("\n")
dest_lines: list[str] = []
orig_index = 0
for chunk in action.chunks:
if chunk.orig_index > len(orig_lines):
raise DiffError(
f"{path}: chunk.orig_index {chunk.orig_index} exceeds file length"
)
if orig_index > chunk.orig_index:
raise DiffError(
f"{path}: overlapping chunks at {orig_index} > {chunk.orig_index}"
)
dest_lines.extend(orig_lines[orig_index : chunk.orig_index])
orig_index = chunk.orig_index
dest_lines.extend(chunk.ins_lines)
orig_index += len(chunk.del_lines)
dest_lines.extend(orig_lines[orig_index:])
return "\n".join(dest_lines)
def patch_to_commit(patch: Patch, orig: dict[str, str]) -> Commit:
commit = Commit()
for path, action in patch.actions.items():
if action.type is ActionType.DELETE:
commit.changes[path] = FileChange(
type=ActionType.DELETE, old_content=orig[path]
)
elif action.type is ActionType.ADD:
if action.new_file is None:
raise DiffError("ADD action without file content")
commit.changes[path] = FileChange(
type=ActionType.ADD, new_content=action.new_file
)
elif action.type is ActionType.UPDATE:
new_content = _get_updated_file(orig[path], action, path)
commit.changes[path] = FileChange(
type=ActionType.UPDATE,
old_content=orig[path],
new_content=new_content,
move_path=action.move_path,
)
return commit
# --------------------------------------------------------------------------- #
# User-facing helpers
# --------------------------------------------------------------------------- #
def text_to_patch(text: str, orig: dict[str, str]) -> tuple[Patch, int]:
lines = text.splitlines() # preserves blank lines, no strip()
if (
len(lines) < 2
or not Parser._norm(lines[0]).startswith("*** Begin Patch")
or Parser._norm(lines[-1]) != "*** End Patch"
):
raise DiffError("Invalid patch text - missing sentinels")
parser = Parser(current_files=orig, lines=lines, index=1)
parser.parse()
return parser.patch, parser.fuzz
def identify_files_needed(text: str) -> list[str]:
lines = text.splitlines()
return [
line[len("*** Update File: ") :]
for line in lines
if line.startswith("*** Update File: ")
] + [
line[len("*** Delete File: ") :]
for line in lines
if line.startswith("*** Delete File: ")
]
def identify_files_added(text: str) -> list[str]:
lines = text.splitlines()
return [
line[len("*** Add File: ") :]
for line in lines
if line.startswith("*** Add File: ")
]
# --------------------------------------------------------------------------- #
# File-system helpers
# --------------------------------------------------------------------------- #
def load_files(paths: list[str], open_fn: Callable[[str], str]) -> dict[str, str]:
return {path: open_fn(path) for path in paths}
def apply_commit(
commit: Commit,
write_fn: Callable[[str, str], None],
remove_fn: Callable[[str], None],
) -> None:
for path, change in commit.changes.items():
if change.type is ActionType.DELETE:
remove_fn(path)
elif change.type is ActionType.ADD:
if change.new_content is None:
raise DiffError(f"ADD change for {path} has no content")
write_fn(path, change.new_content)
elif change.type is ActionType.UPDATE:
if change.new_content is None:
raise DiffError(f"UPDATE change for {path} has no new content")
target = change.move_path or path
write_fn(target, change.new_content)
if change.move_path:
remove_fn(path)
def process_patch(
text: str,
open_fn: Callable[[str], str],
write_fn: Callable[[str, str], None],
remove_fn: Callable[[str], None],
) -> str:
if not text.startswith("*** Begin Patch"):
raise DiffError("Patch text must start with *** Begin Patch")
paths = identify_files_needed(text)
orig = load_files(paths, open_fn)
patch, _fuzz = text_to_patch(text, orig)
commit = patch_to_commit(patch, orig)
apply_commit(commit, write_fn, remove_fn)
return "Done!"
# --------------------------------------------------------------------------- #
# Default FS helpers
# --------------------------------------------------------------------------- #
def open_file(path: str) -> str:
with open(path, "rt", encoding="utf-8") as fh:
return fh.read()
def write_file(path: str, content: str) -> None:
target = pathlib.Path(path)
target.parent.mkdir(parents=True, exist_ok=True)
with target.open("wt", encoding="utf-8") as fh:
fh.write(content)
def remove_file(path: str) -> None:
pathlib.Path(path).unlink(missing_ok=True)
# --------------------------------------------------------------------------- #
# CLI entry-point
# --------------------------------------------------------------------------- #
def main() -> None:
import sys
patch_text = sys.stdin.read()
if not patch_text:
print("Please pass patch text through stdin", file=sys.stderr)
return
try:
result = process_patch(patch_text, open_file, write_file, remove_file)
except DiffError as exc:
print(exc, file=sys.stderr)
return
print(result)
if __name__ == "__main__":
main()その他の有効な差分形式
別の差分形式を試す場合は、Aider の polyglot ベンチマークで使われている SEARCH/REPLACE 差分形式や、内部でエスケープを行わない疑似 XML 形式が候補になります。テストでは、どちらも高い成功率を示しました。
これらの差分形式には、重要な共通点が 2 つあります。(1)行番号を使わないこと、(2)置換対象のコードと置換後のコードの両方を正確に示し、明確な区切り文字で両者を区別することです。
SEARCH_REPLACE_DIFF_EXAMPLE = """
path/to/file.py
```
>>>>>>> SEARCH
def search():
pass
=======
def search():
raise NotImplementedError()
<<<<<<< REPLACE
"""
PSEUDO_XML_DIFF_EXAMPLE = """
`<edit>`
`<file>`
path/to/file.py
`</file>`
`<old_code>`
def search():
pass
`</old_code>`
`<new_code>`
def search():
raise NotImplementedError()
`</new_code>`
`</edit>`
"""














