Forge
Skip to main content

Tutorial: GPT-5.4 Python quickstart using the OpenAI API

Getting set up and running GPT-5.4 on your machine in Python using the OpenAI API.
Last updated: March 6, 2026
GPT-5.4 marks a shift from chat-centric AI to a professional-grade agency. This update focuses on the model's ability to navigate computer interfaces, manage massive tool libraries with minimal token overhead, and process over a million tokens of context. In this guide, we will transition your existing GPT-5.2 workflows to the 5.4 standard.
We will use W&B Weave to track these new professional workflows, specifically focusing on how the model utilizes the new tool search and computer interaction capabilities.

Jump to the tutorial


Table Of Contents


If you're just getting started and don't yet have your machine set up to run Python, I've created a quick tutorial here that will have you up-and-running in just a few minutes.
💡
Once you're set up, you'll need an OpenAI API key. So let's start there:

What's new in GPT-5.4?

The transition from 5.2 to 5.4 introduces several features designed for complex, multi-step professional work:
  • Native computer use: The model can now control a cursor and keyboard directly through a dedicated computer tool.
  • Tool search capability: Instead of loading every tool definition into your prompt, GPT-5.4 can dynamically search for the tools it needs, which can reduce input tokens by nearly half.
  • 1.05M context window: The context limit has been expanded significantly to accommodate massive documents and long-running agentic loops.
  • Original detail vision: A new vision parameter allows for pixel-perfect analysis of dense spreadsheets and user interfaces.
There are 4 models:
  • gpt-5.4: General-purpose work, including complex reasoning, broad world knowledge, and code-heavy or multi-step agentic tasks
  • gpt-5.4-pro: Tough problems that may take longer to solve and need deeper reasoning
  • gpt-5-mini: Cost-optimized reasoning and chat; balances speed, cost, and capability
  • gpt-5-nano: High-throughput tasks, especially straightforward instruction-following or classification
And some of my favorite advancements (and their benchmarks are:
A big leap forward in pulling accurate information from the web

A nice step forward in agentic tool calling

And here's how it stacks up on some key benchmarks



Getting started with the GPT-5.4 API

Before you can use GPT-5 via the API, you'll need a valid API key. Just head to OpenAI’s product page and click "Start building" to begin your signup flow.

After signing up, verify your email and phone number to unlock the dashboard. That's where you can manage your projects and keys.

Creating your OpenAI API key

In the dashboard, click the current project name (e.g., Default project) in the top left:

Once you have a project, go to settings:

...and then to your API keys:

Inside your project, navigate to API keys and click "Create key." You'll be asked to give it a name.

Next, just decide what permissions you'd like it to have. You can read more about these here.
Don't save your key unless you have someone highly secure (a notepad doc on your desktop is not). Once you're used it momentarily, close the notepad doc without saving.
💡

OpenAI pricing for GPT-5.4

GPT-5.4 is priced higher per token than GPT-5.2, but its improved token efficiency means many tasks actually cost less end-to-end due to fewer total tokens required.
ModelInputCached InputOutput
gpt-5.2$1.75 / M tokens$0.175 / M tokens$14 / M tokens
gpt-5.4$2.50 / M tokens$0.25 / M tokens$15 / M tokens
gpt-5.2-pro$21 / M tokens—$168 / M tokens
gpt-5.4-pro$30 / M tokens—$180 / M tokens

Batch and Flex pricing are available at half the standard rate; Priority processing is available at twice the standard rate.

W&B Weave

We'll use W&B Weave to track all of our experiments. By adding the @weave.op() decorator, we automatically capture inputs, outputs, token usage, reasoning metadata, and the new computer-use traces. This gives you a searchable, comparable record of every model call you make.

Tutorial: Getting started with GPT-5.2

You can follow along in Jupyter Notebook, Colab, or any Python REPL.


Step 1: The OpenAI GPT-5.2 API key

Begin by exporting your OpenAI API key as an environment variable:
%env OPENAI_API_KEY=YOUR_KEY_HERE
Replace YOUR_KEY_HERE with your actual value. When you run this in Jupyter, it will echo back the key, confirming it's active.


Step 2: Installing OpenAI and W&B Weave

We need the latest version of the OpenAI library to support the new verbosity and custom tool types in 5.2.
This is a good time to sign up for Weights & Biases, to save you having to interrupt your workflow in a couple minutes, when you're further along.
💡
!pip install --upgrade openai weave
Wait for the cell to finish—the [*] indicator will turn into a number.
💡


Step 3: Import libraries and pass the OpenAI API key

Replace `YOUR_KEY_HERE` with your actual value. When you run this in Jupyter, it will echo back the key, confirming it's active.
import os
import weave
from openai import OpenAI

# Initialize Weave
weave.init('gpt-5.4-tutorial')

# Initialize OpenAI client
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
You'll get something like:


Step 4: Text generation with none Reasoning

GPT-5.4 (like GPT-5.2) supports reasoning={"effort": "none"}, turning the model into a low-latency, high-intelligence responder. This is the default reasoning setting in GPT-5.4 and is perfect for chat apps where speed is critical.
gpt_assistant_prompt = "You are a helpful assistant."
gpt_user_prompt = "Explain quantum entanglement in one sentence."

@weave.op()
def generate_fast_response(assistant_prompt: str, user_prompt: str):
"""Generate text using GPT-5.4's 'none' reasoning effort for max speed"""
response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "none"},
input=[
{"role": "developer", "content": assistant_prompt},
{"role": "user", "content": user_prompt}
]
)
return {
"output_text": response.output_text,
"latency_mode": "lowest (reasoning: none)"
}

fast_result = generate_fast_response(gpt_assistant_prompt, gpt_user_prompt)
print("⚡ Fast Response:", fast_result["output_text"])

With reasoning effort set to none, prompting strategy matters more. Encourage the model to "think through its steps" in your prompt to improve output quality even at this speed setting.
💡
Because we've added the Weave decorator, the data is stored in Weave for future reference and comparison:


Step 5: Controlling output length with Verbosity

Verbosity Control lets you manage output length natively via the API text parameter, no more begging the model to "be concise" in your prompt. Options are low, medium (default), and high.
@weave.op()
def generate_with_verbosity(user_prompt: str, verbosity_level: str):
"""Test GPT-5.4's native verbosity controls"""
response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "low"},
text={"verbosity": verbosity_level},
input=[{"role": "user", "content": user_prompt}]
)
return response.output_text

prompt = "Explain how a bicycle works."

print(f"--- LOW VERBOSITY ---\n{generate_with_verbosity(prompt, 'low')}\n")
print(f"--- HIGH VERBOSITY ---\n{generate_with_verbosity(prompt, 'high')}\n")
When run, these appear as:


Viewing GPT-5 inputs and outputs in W&B Weave

Click the link generated by the cell above to open Weave. In your Traces view, you can directly compare latency, token usage, and cost between verbosity settings. The Inputs/Outputs tab shows exactly what the model received and returned.
This is especially valuable as we move into more complex features. Weave gives you a laboratory notebook for every experiment.

You can also click the tabs in the top right to get additional details, including:


Step 6: GPT-5.4 reasoning spectrum (None to xHigh)

GPT-5.4 expands the reasoning spectrum beyond GPT-5.2, adding xhigh for the deepest analysis:
  • None: Instant responses, chat apps, low-latency pipelines
  • Low/Medium/High: Standard gradient of depth vs. speed
  • xHigh: Deep research, complex architecture generation, and frontier analysis
The most practical question isn't "which level gets the right answer on a trick question" — GPT-5.4 is strong enough that none handles most well-known problems correctly. The real question is: for your workload, where does the quality-vs-cost tradeoff make sense?
Here's how the levels differ in practice:
LevelReasoning tokensChain of ThoughtBest for
none0❌Chat, autocomplete, low-latency pipelines
low / mediumSome✅ partialGeneral Q&A, summarization, standard code gen
highMany✅ fullComplex logic, multi-step problems, debugging
xhighMaximum✅ extendedDeep research, architecture decisions, frontier tasks

The code below runs the same prompt at three levels and logs everything to Weave, where the difference becomes visible, not in whether the answer is right, but in how the model got there and what it cost.
@weave.op()
def compare_reasoning_levels(user_prompt: str):
"""
Run the same prompt at none, high, and xhigh.
Compare in Weave: token usage, latency, and Chain of Thought depth.
"""
levels = ["none", "high", "xhigh"]
results = {}

for level in levels:
print(f"Thinking with {level} effort...")
response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": level},
input=[{"role": "user", "content": user_prompt}]
)
results[level] = {
"answer": response.output_text,
"usage": response.usage.model_dump() if response.usage else {}
}

return results

# Swap in any prompt from your own workload to find your personal sweet spot
your_prompt = "What are the tradeoffs between a message queue and a database for handling async job processing at scale?"

comparison = compare_reasoning_levels(your_prompt)

for level, result in comparison.items():
tokens = result["usage"].get("output_tokens", "n/a")
print(f"\n🧠 {level.upper()} ({tokens} output tokens)")
print(result["answer"])
After running this, open the Weave link and look at three things:
  1. The "Thinking" dropdown: present on high and xhigh traces, absent on none. This is the Chain of Thought the model worked through before answering. For complex prompts, this is often longer and more careful than the final answer itself.
  2. Output token counts: xhigh will use significantly more tokens than none. For simple prompts, the answers may look nearly identical; for genuinely hard ones, the gap in depth will be obvious.
  3. Latency: none responses arrive much faster. If you're building a user-facing product, this is the tradeoff that matters most.
Finding your sweet spot: Start with none and increase only if outputs aren't meeting your quality bar. Most everyday tasks don't need high, and xhigh is best reserved for tasks where you'd want a thoughtful human expert to spend real time on the problem.
💡


Step 7: Structured JSON output with Pydantic

Structured outputs are faster and more reliable in GPT-5.4. The cleanest approach is to use responses.create() with text={"format": {"type": "json_object"}} and validate the result manually with Pydantic. This avoids serialization warnings that can appear when using responses.parse() with the newer SDK, and gives you full control over the parsed output.
import json
from pydantic import BaseModel

class CodeAnalysis(BaseModel):
language: str
complexity_score: int
suggestions: list[str]

@weave.op()
def analyze_code_structure(code_snippet: str):
response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "low"},
text={"format": {"type": "json_object"}},
input=[
{
"role": "developer",
"content": (
"You are a code reviewer. Always respond with a JSON object "
"with fields: language (str), complexity_score (int 1-10), "
"and suggestions (list of strings)."
)
},
{"role": "user", "content": f"Analyze this code: {code_snippet}"}
]
)
# Parse and validate with Pydantic
raw = json.loads(response.output_text)
result = CodeAnalysis(**raw)
return result.model_dump()

snippet = "def add(a,b): return a+b"
analysis = analyze_code_structure(snippet)
print("✅ Structured Data:", analysis)
Which will print:

And of course, sent this to Weave:


Step 8: Advanced agentic workflows with custom tools

GPT-5.4 continues support for type: "custom" tools introduced in GPT-5.2. This lets the model send raw text (Python code, SQL, shell commands, diffs) directly to a tool with no JSON wrapping, no escaped characters, no parsing errors.
tools_list = [{
"type": "custom",
"name": "python_repl",
"description": "Executes arbitrary python code. Input should be raw python code.",
}]

@weave.op()
def agentic_math_solver(problem: str):
"""Solves math by writing and running code using Custom Tools"""

response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "medium"},
tools=tools_list,
tool_choice={
"type": "allowed_tools",
"mode": "required",
"tools": [{"type": "custom", "name": "python_repl"}]
},
input=[
{
"role": "developer",
"content": "You are a Python engine. You calculate answers by executing code."
},
{"role": "user", "content": problem}
]
)

tool_input = None
for item in response.output:
if item.type == "custom_tool_call"
tool_input = item.custom_input # Raw code string — no JSON wrapper
break

if tool_input:
return {
"thought_process": response.output_text,
"generated_code": tool_input,
"status": "success"
}
else:
return {
"thought_process": response.output_text,
"generated_code": "Error: Tool enforcement failed",
"status": "failed"
}

result = agentic_math_solver("Calculate the 12,345th prime number.")
print(f"🤖 Model Thought: {result['thought_process']}")
print(f"💻 Raw Code Generated:\n{result['generated_code']}")
In Weave, inspect the agentic_math_solver trace to see the raw Python script in generated_code - clean, unescaped, and ready to execute.


Step 9: Tool Search: Working with large tool ecosystems (New in GPT-5.4)

One of the biggest new capabilities in GPT-5.4 is Tool Search (deferred tool loading). Previously, all tool definitions had to be included in every prompt upfront, adding thousands of tokens even for tools the model never used. With Tool Search, GPT-5.4 receives a lightweight list of available tools and loads only the definitions it actually needs at runtime.
Why it matters:
  • Reduces token usage by ~47% on tool-heavy workflows (per OpenAI's MCP Atlas benchmark)
  • Preserves prompt cache performance
  • Enables reliable operation across massive tool ecosystems (e.g., large MCP servers)
The API works in two steps: add {"type": "tool_search"} to your tools array, and mark any functions you want deferred with defer_loading: True. The model will load them only when it decides it needs them.
@weave.op()
def tool_search_demo(user_query: str):
"""Demonstrate hosted Tool Search with deferred loading"""

# Group related tools into a namespace — the model sees only the namespace
# name and description upfront; deferred function schemas load on demand
crm_namespace = {
"type": "namespace",
"name": "crm",
"description": "CRM tools for customer lookup and order management.",
"tools": [
{
"type": "function",
"name": "get_customer_profile",
"description": "Fetch a customer profile by customer ID.",
"parameters": {
"type": "object",
"properties": {"customer_id": {"type": "string"}},
"required": ["customer_id"],
"additionalProperties": False,
},
},
{
"type": "function",
"name": "list_open_orders",
"description": "List open orders for a customer ID.",
# defer_loading means this schema is NOT sent upfront —
# it's loaded only if the model decides it needs it
"defer_loading": True,
"parameters": {
"type": "object",
"properties": {"customer_id": {"type": "string"}},
"required": ["customer_id"],
"additionalProperties": False,
},
},
],
}

response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "low"},
tools=[
crm_namespace,
{"type": "tool_search"}, # activates hosted tool search
],
parallel_tool_calls=False,
input=[{"role": "user", "content": user_query}]
)

# The response output will include tool_search_call and tool_search_output
# items showing exactly which tools were loaded — and which weren't
for item in response.output:
if hasattr(item, "type") and "tool_search" in item.type:
print(f"🔍 {item.type}: {item}")

return {
"output": response.output_text,
"output_items": [getattr(i, "type", "unknown") for i in response.output]
}

result = tool_search_demo("List open orders for customer CUST-12345.")
print(f"\n🔧 Output: {result['output']}")
print(f"📊 Response item types: {result['output_items']}")

Inspecting the "Thinking" process in Weave

When the model needs list_open_orders, the response includes a tool_search_call and tool_search_output item before the actual function call, proof that the schema was fetched on demand rather than sent upfront. get_customer_profile, which wasn't needed, was never loaded.
In Weave, compare the input token counts between this call and Step 8 (where all tool schemas were declared upfront). The more tools you add to the namespace, the more pronounced the savings.
Tool Search is most impactful when you have 10+ tools or are working with MCP servers. For 2–3 tools, standard tool definitions are fine.
💡


Step 10: Computer Use: Agents that operate software (New in GPT-5.4)

GPT-5.4 introduces native Computer Use—the ability for the model to "see" a screen via screenshots and return precise mouse and keyboard actions. Unlike previous vision models that could only describe an image, GPT-5.4 can execute a multi-turn loop to complete complex tasks in a live browser or desktop environment.
In this step, we'll build a complete Computer Use harness using Playwright. Our agent will navigate the OpenAI documentation, find the Models page, and list every model it sees.

The Computer Use loop

Operating a computer requires a specialized loop. GPT-5.4 doesn't just give one answer; it enters a dialogue with your system:
  • Observe: Your script captures a screenshot of the current state.
  • Think & act: GPT-5.4 analyzes the screenshot and returns a computer_call containing actions like click, type, or scroll.
  • Execute: Your script performs those actions using a tool like Playwright.
  • Repeat: Capture a new screenshot and send it back to the model until the task is finished.

Implementation: Automating the docs

We'll use W&B Weave to track the entire trajectory, including every screenshot the model used to make its decisions. This provides a pixel-perfect audit trail of the agent's behavior.
import os
import base64
import time
import io
import weave
from PIL import Image
from openai import OpenAI
from playwright.sync_api import sync_playwright

weave.init('gpt-5.4-tutorial')

client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
TARGET_URL = "https://platform.openai.com/docs/"


def capture_screenshot(page):
return page.screenshot(type="png")


def get(action, key, default=None):
"""Get a field from either a dict or an object."""
if isinstance(action, dict):
return action.get(key, default)
return getattr(action, key, default)


def handle_computer_actions(page, actions):
for action in actions:
atype = get(action, 'type')
print(f" Executing action: {atype}")
match atype:
case "click":
page.mouse.click(get(action, 'x'), get(action, 'y'), button=get(action, "button", "left"))
case "double_click":
page.mouse.dblclick(get(action, 'x'), get(action, 'y'), button=get(action, "button", "left"))
case "scroll":
page.mouse.move(get(action, 'x'), get(action, 'y'))
page.mouse.wheel(get(action, "scrollX", 0), get(action, "scrollY", 0))
case "keypress":
KEY_MAP = {
"SPACE": " ", "PAGEDOWN": "PageDown", "PAGEUP": "PageUp",
"RETURN": "Enter", "ESC": "Escape", "TAB": "Tab",
"DELETE": "Delete", "BACKSPACE": "Backspace",
"ALT": "Alt", "CTRL": "Control", "META": "Meta",
"SHIFT": "Shift", "ARROWUP": "ArrowUp", "ARROWDOWN": "ArrowDown",
"ARROWLEFT": "ArrowLeft", "ARROWRIGHT": "ArrowRight",
"HOME": "Home", "END": "End",
}
for key in get(action, 'keys', []):
mapped = KEY_MAP.get(key.upper(), key)
try:
page.keyboard.press(mapped)
except Exception as e:
print(f" (skipping unmapped key '{key}': {e})")
case "type":
page.keyboard.type(get(action, 'text'))
case "wait":
time.sleep(2)
case "screenshot":
pass # handled by caller
case "move":
page.mouse.move(get(action, 'x'), get(action, 'y'))
case "drag":
# API returns path[] array of {x, y} points
path = get(action, 'path', [])
if path:
start = path[0]
end = path[-1]
sx = start.get('x') if isinstance(start, dict) else getattr(start, 'x', 0)
sy = start.get('y') if isinstance(start, dict) else getattr(start, 'y', 0)
ex = end.get('x') if isinstance(end, dict) else getattr(end, 'x', 0)
ey = end.get('y') if isinstance(end, dict) else getattr(end, 'y', 0)
page.mouse.move(sx, sy)
page.mouse.down()
page.mouse.move(ex, ey)
page.mouse.up()
else:
print(f" (drag: no path data, raw action: {action})")
case _:
print(f" (unsupported action type: {atype}, skipping)")


def send_screenshot(response, call_id, screenshot_bytes):
screenshot_b64 = base64.b64encode(screenshot_bytes).decode("utf-8")
return client.responses.create(
model="gpt-5.4",
tools=[{"type": "computer"}],
previous_response_id=response.id,
input=[
{
"type": "computer_call_output",
"call_id": call_id,
"output": {
"type": "computer_screenshot",
"image_url": f"data:image/png;base64,{screenshot_b64}",
"detail": "original",
},
}
],
)


@weave.op()
def get_session_screenshots(screenshot_bytes_list: list) -> list:
"""Convert a list of raw PNG bytes into PIL Images and return them."""
return [Image.open(io.BytesIO(b)) for b in screenshot_bytes_list]


def computer_use_loop(page, response, max_turns=15):
turn = 0
all_screenshots = [] # collect raw PNG bytes every turn

while turn < max_turns:
turn += 1
print(f"\n--- Turn {turn} ---")
print(f"Output item types: {[getattr(i, 'type', '?') for i in response.output]}")

computer_call = next(
(item for item in response.output if item.type == "computer_call"), None
)

if computer_call is None:
print("No more computer_call items — task complete.")
break

print(f"Actions in this call: {[get(a, 'type', '?') for a in computer_call.actions]}")
handle_computer_actions(page, computer_call.actions)

time.sleep(1)
screenshot = capture_screenshot(page)
all_screenshots.append(screenshot)

shot_path = f"./screenshot_turn_{turn}.png"
with open(shot_path, "wb") as f:
f.write(screenshot)
print(f" Screenshot saved: screenshot_turn_{turn}.png")

response = send_screenshot(response, computer_call.call_id, screenshot)

# Return PIL images via weave-tracked function
pil_images = get_session_screenshots(all_screenshots)
print(f"\nTotal screenshots captured: {len(pil_images)}")
for i, img in enumerate(pil_images):
print(f" Turn {i+1}: {img.size[0]}x{img.size[1]} px")

return response, pil_images


@weave.op()
def run_computer_use_task(url: str, query: str) -> dict:
"""
Navigate to a URL, run a computer-use agent with the given query,
and return the model's text response plus a list of PIL screenshots.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page(viewport={"width": 1280, "height": 800})

print(f"Navigating to {url} ...")
page.goto(url, wait_until="networkidle")
time.sleep(2)

screenshot = capture_screenshot(page)
screenshot_b64 = base64.b64encode(screenshot).decode("utf-8")

with open("./screenshot_turn_0.png", "wb") as f:
f.write(screenshot)
print("Initial screenshot saved: screenshot_turn_0.png")

print(f"\nQuery: {query}")
print("Sending to gpt-5.4...")
response = client.responses.create(
model="gpt-5.4",
tools=[{"type": "computer"}],
input=[
{
"role": "developer",
"content": (
"You are a computer-use agent operating a browser at 1280x800. "
"Use the computer tool for all UI interaction."
)
},
{
"role": "user",
"content": [
{
"type": "input_image",
"image_url": f"data:image/png;base64,{screenshot_b64}",
"detail": "original",
},
{
"type": "input_text",
"text": query,
}
]
}
],
)

final_response, pil_images = computer_use_loop(page, response, max_turns=25)
browser.close()

return {
"response": final_response.output_text,
"screenshots": pil_images,
}


def main():
result = run_computer_use_task(
url=TARGET_URL,
query=(
"Navigate to the Models section of this documentation site. "
"You can find it in the left sidebar or by clicking a Models link. "
"Once on the Models page, scroll through the entire page to find all available models. "
"List every single model name you can see."
),
)

print("\n" + "=" * 60)
print("FINAL OUTPUT FROM MODEL:")
print("=" * 60)
print(result["response"])
print(f"\nTotal screenshots: {len(result['screenshots'])}")
for i, img in enumerate(result["screenshots"]):
print(f" Turn {i+1}: {img.size[0]}x{img.size[1]} px")



if __name__ == "__main__":
main()
You'll see the following in Jupyter:



Viewing the agent's trajectory in Weave

Once the agent completes its task, click the Weave link generated in your notebook. Unlike standard chat logs, a Computer Use trace provides a pixel-perfect "replay" of exactly how the agent navigated the interface.
What to look for in your Traces:
  • Input image timeline: In the run_computer_use_task trace, you can click through each turn to see the screenshots the model received. This allows you to verify if the model successfully identified the "Models" link in the sidebar or if it got stuck on a cookie consent banner.
  • Structured tool calls: Look for the computer_call items. Weave displays the exact coordinates (x,yx, y) and action types (click, type, scroll) the model generated.
  • Original detail vision: You can inspect the image inputs to see the "Original" detail level in action. This is what allowed the model to read the small, dense text in the OpenAI documentation without making a mistake.
Enjoy exploring.

Safety note: Always run computer-use agents in an isolated browser or VM, never against your own logged-in accounts or production systems without explicit safeguards.
💡

Step 11: Native compaction for long agent trajectories (New in GPT-5.4)

GPT-5.4 is the first mainline model trained to support Native Compaction, the ability to intelligently summarize earlier turns in a conversation, preserving key context while freeing up space for continued work. Without it, long-running agents either hit the context limit mid-task or start degrading in quality as earlier context gets crowded out.
To use Native Compaction, you must set store=True. If store is set to False, the server deletes the compaction record immediately after the request, and your next turn will fail with a NotFoundError because the model can no longer find that "compressed" history.
💡
There are two approaches depending on how much control you need:
Option A - Server-side compaction (simplest): Pass context_management with a compact_threshold on your responses.create call. When the rendered token count crosses that threshold, the server compacts automatically mid-stream and continues, no extra calls needed.
@weave.op()
def long_running_agent(task_steps: list[str]):
conversation = []

for i, step in enumerate(task_steps):
print(f"--- Step {i+1}: {step[:60]}... ---")

# 1. Add the new user message as an item
conversation.append({"type": "message", "role": "user", "content": step})

response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "medium"},
# Trigger compaction automatically once context exceeds 100k tokens
context_management=[{"type": "compaction", "compact_threshold": 100000}],
input=conversation,
# CRITICAL: Must be True to allow the server to reference compaction items
store=True
)

# 2. Append all output items (including any compaction item) to history
# This is vital: the compaction item carries the 'memory' to the next turn.
conversation.extend(response.output)
print(f" {response.output_text[:100]}...")

return {"steps_completed": len(task_steps)}

steps = [
"Load the sales dataset and describe its structure.",
"Identify the top 5 products by revenue in Q4 2025.",
"Calculate the month-over-month growth rate for those 5 products.",
"Flag any products showing a decline of more than 10%.",
"Write a summary memo suitable for a VP of Sales."
]

result = long_running_agent(steps)
print(f"Completed {result['steps_completed']} steps")
Option B - Standalone compaction (explicit control): When you want to decide exactly when to compact, call client.responses.compact() directly.
import warnings
# Suppress Pydantic warnings caused by new GPT-5.4 item types
warnings.filterwarnings("ignore", category=UserWarning, module="pydantic")

@weave.op()
def long_running_agent(task_steps: list[str]):
# Use a consistent name for our history
history = []

for i, step in enumerate(task_steps):
print(f"--- Step {i+1}: {step[:60]}... ---")
# Add the user message
history.append({"type": "message", "role": "user", "content": step})

response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "medium"},
# Trigger compaction automatically at 100k tokens
context_management=[{"type": "compaction", "compact_threshold": 100000}],
input=history,
store=True # Required for Native Compaction and Reasoning persistence
)

# CRITICAL: Extend with the FULL output (Reasoning item + Message item)
history.extend(response.output)
print(f" {response.output_text[:100]}...")

return history

steps = [
"Load the sales dataset and describe its structure.",
"Identify the top 5 products by revenue in Q4 2025.",
"Calculate the growth rate for those 5 products.",
"Flag any products showing a decline of more than 10%.",
"Write a summary memo for a VP of Sales."
]

# Run the agent and save the full history
full_history = long_running_agent(steps)

# --- Option B: Manual Compaction for the Final Step ---

# 1. Trigger standalone compaction on the full history
compacted = client.responses.compact(
model="gpt-5.4",
input=full_history
)

# 2. Start the next turn with the compacted "anchor"
next_input = [
*compacted.output,
{"type": "message", "role": "user", "content": "Now, give me one final executive summary."}
]

# 3. Final call using store=True
response = client.responses.create(
model="gpt-5.4",
input=next_input,
store=True
)

print(f"✅ Manual Compaction Complete. Summary: {response.output_text[:100]}...")
In your W&B Weave dashboard, open a trace from a long-running agent. You will see a specific compaction item appearing in the output once your threshold is hit. This is a clear signal that the model is managing its own context window rather than letting it balloon toward the limit. You'll notice the input token count for the next turn is significantly lower, even though the model "remembers" everything.



Step 12: Comprehensive tutorial summary

For the final step, we'll generate a personalized summary using the highest reasoning settings, xhigh effort combined with high verbosity, to get the most thorough analysis possible.
@weave.op()
def create_personalized_tutorial_summary(assistant_prompt: str, user_prompt: str) -> dict:
"""Generate a personalized summary using xHigh Reasoning + High Verbosity"""

summary_request = """
Based on our tutorial session, please summarize what we accomplished with GPT-5.4's features:

1. "None" Reasoning effort — the low-latency default
2. Verbosity Controls (Low vs High)
3. Expanded Reasoning Spectrum (None → xHigh)
4. Custom Tools with Raw Text Payloads (type="custom")
5. Tool Search — deferred tool loading for large ecosystems
6. Computer Use — agents that operate software via screenshots
7. Native Compaction — managing long agent trajectories

Reflect on how Tool Search and Computer Use specifically expand what's possible
compared to GPT-5.2.
"""

response = client.responses.create(
model="gpt-5.4",
reasoning={"effort": "xhigh"}, # New in 5.4 — deepest reasoning
text={"verbosity": "high"},
input=[
{
"role": "developer",
"content": f"{assistant_prompt} Provide a thoughtful, comprehensive summary."
},
{
"role": "user",
"content": summary_request
}
]
)

return {
"personalized_summary": response.output_text,
"tutorial_features": [
"Reasoning: None (Instant default)",
"Verbosity Controls",
"Reasoning Spectrum: None → xHigh",
"Custom Tools (Raw Inputs)",
"Tool Search (Deferred Loading)",
"Computer Use (Native)",
"Native Compaction",
"Weave Tracing"
]
}

final_summary = create_personalized_tutorial_summary(gpt_assistant_prompt, gpt_user_prompt)

print("🎯 Your Personalized GPT-5.4 Summary:")
print(final_summary["personalized_summary"])
In Weave, the xhigh trace will include a dedicated Reasoning Item in the timeline, capturing the model's full internal logic and 'Chain of Thought' before it commits to an answer. Combined with high verbosity, the final output shifts from a simple bulleted list to a structured, professional-grade executive recap.


Step 13: Reviewing your work in Weave

After running through this tutorial, your Weave dashboard has become a comprehensive laboratory notebook. Every function decorated with @weave.op() has been automatically logged.
Here's what to look for:
  • Latency comparisons: Compare Step 4 (reasoning: none) vs Step 13 (reasoning: xhigh) to see the full speed/depth tradeoff in action
  • Verbosity tokens: Check Step 5 usage stats to see exactly how many more tokens High verbosity uses vs Low
  • Tool Search savings: In the Step 10 trace, compare input token counts vs a standard tool call to see the deferred loading savings
  • Computer Use traces: In Step 11, inspect the screenshot input alongside the structured action output for full auditability
  • Compaction efficiency: In Step 12, watch how token usage per turn stabilizes as compaction kicks in over a long trajectory
  • xHigh reasoning: In Step 13, open the "Thinking" dropdown to see GPT-5.4's full chain-of-thought before the final answer

Conclusion

We've just explored GPT-5.4's most powerful capabilities, going well beyond simple text generation. To summarize, we learned how to:
  • Slash latency: Use reasoning={"effort": "none"} for instant, chat-like experiences (the new default)
  • Control output size: Use text={"verbosity": "low"} for efficient machine-to-machine communication, or high for rich explanations
  • Go deeper: Use reasoning={"effort": "xhigh"} for frontier-level analysis, research, and complex architecture generation
  • Build robust agents: Use type="custom" tools to send raw code, SQL, or patches without parsing errors
  • Scale tool ecosystems: Use Tool Search to reduce token usage by ~47% on large tool surfaces without sacrificing accuracy
  • Operate software: Use the built-in Computer Use tool to let agents complete real tasks across browsers and desktops
  • Run long trajectories: Use Native Compaction to manage context intelligently across extended multi-step workflows
GPT-5.4 isn't just smarter, it's more controllable, more efficient, and capable of operating in the real world in ways its predecessors couldn't. The combination of Tool Search, Computer Use, and Native Compaction makes it the best model yet for building reliable, long-running agents and complex professional workflows.
Let us know in the comments what you plan to build with these new capabilities.