Forge
Skip to main content

Tutorial: GPT-5.2 Python quickstart using the OpenAI API

Getting set up and running GPT-5.2 on your machine in Python using the OpenAI API.
Last updated: March 5, 2026
In this tutorial, you'll learn about GPT-5.2's most powerful features in under 15 minutes. We'll explore the updated Responses API, create guaranteed JSON outputs with Pydantic, and dive into exclusive 5.2 features like Verbosity Controls, Custom Tools (free form inputs), and the new "None" to "xHigh" reasoning spectrum. We'll log everything with W&B Weave for complete visibility into your AI workflow.
By the end, you should have some fresh ideas about building or upgrading your production-ready applications to the new standard.

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're going to need an OpenAI API. So let's start there:

Getting started with the GPT-5.2 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.2

GPT-5.2 introduces a more granular pricing model based on reasoning effort. While gpt-5-mini remains the cost-leader, gpt-5.2 allows you to pay less for low-latency queries (reasoning set to "none") and more for deep-thought queries (reasoning set to "high" or "xhigh").


W&B Weave

We'll be using W&B Weave to track our experimental 5.2 features. By adding the @weave.op() decorator, we capture inputs, outputs, tokens, and the new reasoning metadata automatically.

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=KEY
Replace the bold KEY above with the your 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
...and then run the cell.
Wait for the cell to finish—the [*] indicator will turn into a number.
💡

At this point, we've installed it, but we still need to import it for use
If you're new to Python, basically when we install a library we simply grab the code. When we import it, we make that library available for use.

I read a great explanation once. Installing is like uploading an image to a server. Importing is like embedding that image on a page once it's available.
💡

Step 3: Import libraries and pass the OpenAI API key

Next, load your packages and set up both Weave and the OpenAI client:
import os
import weave
from openai import OpenAI

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

# Initialize OpenAI client
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

Step 4: Text generation (the "none" reasoning breakthrough)

In previous models, there was always some latency for reasoning. GPT-5.2 introduces reasoning={"effort": "none"}. This turns GPT-5.2 into a low-latency, high-intelligence responder, 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.2's new 'none' reasoning effort for max speed"""
response = client.responses.create(
model="gpt-5.2",
# NEW in 5.2: 'none' effort for lowest latency
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"])



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

One of the most requested features in 5.2 is Verbosity Control. Instead of begging the model in the prompt to "be concise" or "explain in detail," you can now control this via the API text parameter.
Options are low, medium (default), and high.
@weave.op()
def generate_with_verbosity(user_prompt: str, verbosity_level: str):
"""Test GPT-5.2's native verbosity controls"""
response = client.responses.create(
model="gpt-5.2",
reasoning={"effort": "low"}, # minimal reasoning
# NEW in 5.2: Native verbosity control
text={"verbosity": verbosity_level},
input=[{"role": "user", "content": user_prompt}]
)
return response.output_text

prompt = "Explain how a bicycle works."

# Compare Low vs High verbosity
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. You will see your Traces, where you can easily compare important metrics like latency, tokens and cost between verbosity settings.

Why this matters: low verbosity is excellent for generating SQL queries or code snippets without the "fluff," while high is perfect for educational tutors.
💡
You can also click the tabs in the top right to get additional details, including:


Step 7: GPT-5.2 reasoning spectrum (None to xHigh)

GPT-5.2 expands the reasoning capabilities. We now have access to:
  • None: Instant, no "thought" tokens.
  • Low/Medium/High: The standard gradient.
  • xHigh: (New) For deep research or complex architecture generation.
Let's test the extremes.
@weave.op()
def compare_reasoning_extremes(user_prompt: str):
levels = ["none", "high"] # xhigh is available on gpt-5.2-pro
results = {}
for level in levels:
print(f"Thinking with {level} effort...")
response = client.responses.create(
model="gpt-5.2",
reasoning={"effort": level},
input=[{"role": "user", "content": user_prompt}]
)
results[level] = response.output_text
return results

complex_prompt = "Write a Python script that calculates the fibonacci sequence using dynamic programming, and explain the time complexity."

comparison = compare_reasoning_extremes(complex_prompt)

print(f"\n🧠 NONE Effort:\n{comparison['none'][:150]}...")
print(f"\n🧠 HIGH Effort:\n{comparison['high'][:150]}...")
In Weave, you will notice the "High" effort trace includes a "Chain of Thought" section that is hidden from the final output but was used to generate the answer.


Step 8: Structured JSON output with Pydantic

Structured outputs remain a staple in 5.2, but the back end is faster and more reliable.
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.parse(
model="gpt-5.2",
input=[
{"role": "developer", "content": "You are a code reviewer."},
{"role": "user", "content": f"Analyze this code: {code_snippet}"}
],
text_format=CodeAnalysis
)
return response.output_parsed.model_dump()

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



Step 9: Advanced Agentic Workflows with Custom Tools

This is the biggest change in GPT-5.2. Previously, tools required structured JSON. Now, GPT-5.2 supports type: "custom".
This allows the model to send raw text (e.g., Python code, SQL, or a diff patch) directly to a tool, without wrapping it in a JSON string. This significantly reduces errors in code generation.
We will use tool_choice="required" to force the tool call, and access the raw code via the .input attribute.
# Define the Custom Tool with type="custom"
tools_list = [{
"type": "custom", # NEW in 5.2
"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.2",
reasoning={"effort": "medium"},
tools=tools_list,
# NEW: Strictly force the model to use the tool
# This prevents the model from just answering with text
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}
]
)
# Iterate through outputs to find the tool call
# (GPT-5.2 often outputs thought text first, then the tool)
tool_input = None
for item in response.output:
if item.type == "tool_call":
tool_input = item.custom_input # This is the raw code string
break
# Always return a structured dict to avoid TypeErrors in print statements
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"
}

# Ask a hard question that requires calculation
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']}")
After running the cell, click the link to open your Weave dashboard and inspect the agentic_math_solver trace. This view confirms that our new architecture is working.
Notice that the generated_code field contains a raw Python script. In previous API versions, this output was wrapped in a JSON object (e.g., {"code": "import..."}), which often caused syntax errors due to escaped characters. By using type: "custom", we have successfully forced GPT-5.2 to skip the JSON wrapper and deliver pure code, as shown below:



Step 10: Comprehensive tutorial summary

For our final step, we'll create a personalized summary of everything we've accomplished. We will use the highest settings available to standard users to get the most thoughtful analysis.
We will combine High Reasoning (to think deeply about what we learned) with the new High Verbosity setting (to ensure the model explains every detail thoroughly).
@weave.op()
def create_personalized_tutorial_summary(assistant_prompt: str, user_prompt: str) -> dict:
"""Generate a personalized summary using High Reasoning + High Verbosity"""
summary_request = f"""
Based on our tutorial session, please summarize what we accomplished with GPT-5.2's new features:
1. "None" Reasoning effort (The latency breakthrough)
2. Verbosity Controls (Low vs High)
3. Custom Tools with Raw Text Payloads (type="custom")
4. "Required" Tool Choice (Forcing agentic behavior)
Reflect on how 'Custom Tools' specifically improves upon previous JSON-based tools.
"""
response = client.responses.create(
model="gpt-5.2",
# Use High effort for deep analysis
reasoning={"effort": "high"},
# NEW in 5.2: Force a verbose, detailed explanation
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)",
"Verbosity Controls",
"Custom Tools (Raw Inputs)",
"Tool Choice: Required",
"Weave Tracing"
]
}

# We reuse the prompts from earlier in the tutorial
final_summary = create_personalized_tutorial_summary(gpt_assistant_prompt, gpt_user_prompt)

print("🎯 Your Personalized GPT-5.2 Summary:")
print(final_summary["personalized_summary"])

Inspecting the "Thinking" process in Weave

Because we set reasoning={"effort": "high"}, GPT-5.2 didn't just generate text; it thought through the tutorial's structure before answering. In Weave, you can actually see this process.

In the trace view above, notice two key things:
  1. The "Thinking" dropdown: This proves the model performed a Chain of Thought (CoT) before generating the final answer.
  2. High verbosity: Because we set text={"verbosity": "high"}, the output is a detailed, structured recap ("Below is a structured recap...") rather than a quick summary.

Verifying structured data capture

Weave also captures the structured data we returned from our function. Switch to the Inputs/Outputs tab in your trace to see the clean list of features we mastered:


This view confirms that Weave successfully logged the tutorial_features list, giving you a perfect record of the capabilities tested in this session: Reasoning, Verbosity, Custom Tools, and Tool Choice.

Step 11: 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.
In the dashboard, you can now see the specific GPT-5.2 improvements we tested:
  • Latency comparisons: Compare the execution time of Step 4 (Reasoning: none) vs Step 7 (Reasoning: high).
  • Verbosity tokens: Check the usage stats on Step 5 to see exactly how many more tokens "High Verbosity" uses compared to "Low."
  • Raw code payloads: In the trace for Step 9, inspect the custom_tool_call to see the clean, raw Python code that the model generated, free of JSON formatting.
  • Tool enforcement: Verify that tool_choice="required" successfully forced a tool call where the model might otherwise have been lazy.

Conclusion

We've just learned about GPT-5.2's most powerful new capabilities and moved beyond simple text generation. To sum up, we learned how to:
  • Slash latency: Use reasoning={"effort": "none"} for instant, chat-like experiences.
  • Control output size: Use text={"verbosity": "low"} for efficient machine-to-machine communication, or high for rich explanations.
  • Build robust agents: Use type="custom" tools to let the model write raw code, SQL, or patches without parsing errors.
  • Enforce behavior: Use tool_choice="required" to guarantee your agents take action instead of just talking.
GPT-5.2 isn't just smarter; it's more controllable. The ability to send raw text to tools and strictly enforce their usage makes it the best model yet for building reliable coding agents and complex workflows.
Let us know in the comments below what you plan to build with these new agentic features!