Hoppa till huvudinnehållet

OpenAI's GPT-6.2 API Tutorial: Analyze Charts With Sol and Astra

Build a Python chart explainer using GPT-6.2 Sol and Astra, check model claims against source data, and compare accuracy, publication readiness, and API costs.
· 14 min läs

Utforska med AI

Lägg till DataCamp som föredragen källa på Google

A chart can be clear on screen and still leave someone using a screen reader guessing at the numbers. I wanted to see whether GPT-6.2 Sol and GPT-6.2 Astra can turn an exported chart into an accurate, publishable text alternative, and whether adding the original spreadsheet changes the result.

To test that, I built a Python tool around a synthetic 12-week chart for a fictional platform called LearnFlow, with a late crossover, a missing week, and a 50% axis floor. Both models return short alternative (alt) text, a long description, and structured claims, which Python checks against the spreadsheet before a quick human review. LearnFlow is just the example here, and the same workflow applies whenever you have reliable data behind a chart you plan to publish.

Using basic Python and a little API experience, you'll build this workflow with the OpenAI application programming interface (API) and learn how to:

  • Set factual and readability checks before calling either model
  • Send a chart image to GPT-6.2 Sol and Astra and parse structured text back
  • Check numeric claims against your data and calculate cost from API usage
  • Publish the chart, reviewed description, and data table together in HTML

Our GPT-6.2 Astra and Sol overview covers the launch and benchmark scores, while this tutorial tests one chart task those benchmarks leave open.

TL;DR

I sent the synthetic LearnFlow chart to GPT-6.2 Sol and GPT-6.2 Astra three times on its own, then repeated the request with the source CSV (comma-separated values) included as text. Both models passed every factual check after human review, yet none of the 12 outputs was ready to publish unchanged.

  • All 12 descriptions met the 8-fact rubric with 0 unsupported claims after human review, while attaching the CSV turned approximate wording ("about 58%") into exact figures without changing factual scores.
  • Factual accuracy did not equal publication readiness: every reply missed how a 50% axis floor exaggerates visual gaps, and one Sol output listed all 35 available data points in prose.
  • On image-only calls, Sol averaged $0.0158 per structured response versus $0.0490 for Astra (about 3.1 times higher despite 4x token rates), with median latency between 14.5 and 17.3 seconds across all four setups.

What Changes in the GPT-6.2 API

Both GPT-6.2 Astra (gpt-6.2-astra) and GPT-6.2 Sol (gpt-6.2-sol), introduced in OpenAI's GPT-6.2 launch post, read images and support Structured Outputs (replies locked to a fixed JSON layout) on the Responses API. Those vision and structured-output abilities carry over from earlier models, while three API details matter for this project:

  • Reasoning effort (how much thinking the model does before answering): OpenAI's GPT-6.2 guide suggests starting at reasoning.effort = "medium", and the API rejects none.
  • Simpler request settings: Responses API calls drop randomness controls like temperature, top_p, and top_logprobs. Both models also support contexts up to 1,050,000 tokens (the pieces of text a model reads and writes).
  • Fourfold price gap: on OpenAI's API pricing page, Standard short-context rates per million tokens are $2 input, $0.10 cached input, and $10 output for Sol, versus $8, $0.40, and $40 for Astra.

Every call here holds reasoning.effort at medium so both models run on equal footing.

Build an Accessible Chart Alt Text Generator With the GPT-6.2 API

The LearnFlow Chart Explainer is a Python chart alt text generator that takes a chart PNG, plus an optional CSV table, and returns short alt text, a long description, structured claims, and a list of uncertainties. That two-part format follows the World Wide Web Consortium (W3C) complex images tutorial: short alt text identifies the chart, while the long description gives its scales, values, relationships, and trends.

Architecture diagram of the LearnFlow Chart Explainer: a chart PNG and optional CSV enter a single Python function calling the OpenAI Responses API with GPT-6.2 Sol or Astra and a Pydantic schema, producing structured claims checked in Python against the hidden CSV before a quick human review publishes an accessible HTML figure and data table.

Chart image in, reviewed HTML out. Image by Author.

Before writing API code, we need a chart that tests common reading mistakes.

Three chart traps that trip up AI descriptions

LearnFlow is a synthetic dataset of weekly 30-day course completion rates for Python, SQL, and Power BI across 12 weekly cohorts, built with three traps:

  • A crossover: SQL climbs from 58% in week 1 to 81% in week 12 and passes Python in week 11.
  • A missing week: SQL has no value in week 8, so calling it a drop invents a dip.
  • A non-zero axis: the vertical axis starts at 50%, making gaps look wider than they would from 0%.

Watch the units too. SQL's rise from 58% to 81% is 23 percentage points (the plain difference between two percentages), while relative to 58% it is nearly a 40% jump.

Plotting week 8 carefully matters too. pandas reads the blank cell as NaN ("not a number"). Per the Matplotlib docs, keeping NaN breaks the line cleanly, whereas dropping the row bridges weeks 7 and 9 and filling it with 0 draws a fake dip.

Line chart titled LearnFlow: share of each weekly cohort that completed its course within 30 days. Three lines span enrollment cohort weeks 1 to 12 on a vertical axis from 50% to 90%: Python with blue circles, SQL with orange squares, and Power BI with green triangles, each labeled at its right end. The SQL line has a gap at week 8 and crosses above Python between weeks 10 and 11.

The one chart both models read. Image by Author.

Each line also uses its own marker and end label, following W3C's use of color guideline so color is never the only cue.

Verify AI-generated chart descriptions against source data

Sounding right is not enough. Define ground truth (the verified facts) from the CSV first, keep those facts out of the prompt, and check every reply against a fixed list so short answers can't hide omissions:

Check category

What the description must capture (LearnFlow example)

Chart identity

Line chart of 30-day completion for Python, SQL, and Power BI over 12 weekly cohorts

Main trend

SQL rises across the 12-week period

Endpoints

SQL starts near 58% in week 1 and ends near 81% in week 12

Key crossover

SQL first passes Python in week 11 (or between weeks 10 and 11)

Missing data

SQL has no value in week 8 (reported as missing data)

Axis scale

Vertical axis starts at 50%

Python series

Python stays near 72% to 78% and eases at the end

Power BI series

Power BI drifts down from about 66% to about 60%

Pixel estimates get a 2-percentage-point margin since gridlines sit 5 points apart. Python checks structured track-week-value claims against the CSV, while human review confirms all 8 facts in context and judges readiness to publish.

Every description must clear four factual checks (our 200-character alt text limit is for conciseness; W3C sets no fixed cap):

  • Complete with no API refusal
  • Include all 8 facts above
  • Keep short alt text to 200 characters or fewer
  • Contain 0 unsupported claims (values outside tolerance, invented week 8 data, wrong crossover or axis floor, or made-up causes)

Print those computed facts and the pass rule in your terminal first:

PowerShell terminal output running the Python checker before any API call, confirming the chart PNG hash match, printing the computed reference facts from the CSV including the week 8 missing SQL value and week 11 crossover, and displaying the pass rule.

Ground-truth facts printed before API calls. Image by Author.

With the chart and scoring rules fixed, we can set up Python and send our first requests.

Set Up GPT-6.2 Chart Analysis in Python

To run AI chart analysis in Python with the OpenAI API, you need Python 3.11 or newer, an API key, and openai 3.53.0 or later. Clone the GitHub repository for the sample chart, checker helpers, and Streamlit web viewer, then install the packages in a virtual environment:

git clone https://github.com/KhalidAbdelaty/gpt-6-2-chart-analysis-api.git
cd gpt-6-2-chart-analysis-api
python -m venv .venv
source .venv/bin/activate          # Windows: .venv\Scripts\Activate.ps1
pip install -r requirements.txt    # openai 3.55.1, pandas 3.1.1, matplotlib 3.11.2, pydantic 2.14.3

Put OPENAI_API_KEY=... in a .env file kept out of Git. Every API call in the project goes through one function, describe_chart().

Send a chart image with the OpenAI Responses API

Each request sends two messages. Put shared instructions first in a developer message instead of the top-level instructions field: starting with GPT-6.2, OpenAI places top-level instructions after input, which leaves them outside prompt caching (a discount for repeated prompt openings). The user message holds the task, the chart PNG as Base64 (a text format for sending files inside JSON), and optionally the CSV text.

The detail setting controls image resolution: lower settings use fewer tokens, while high keeps small markers and labels clear. Because OpenAI's Images and vision guide lists no GPT-6.2 image token counts yet, I used detail="high" and calculated each call's cost from the token counts in response.usage using OpenAI's Standard rates.

Here is the core Responses API call inside describe_chart() (the full helper in the repository adds the prompt text, image loader, and error, refusal, timing, and cost handling):

content = [
    {"type": "input_text", "text": TASK_TEXT},  # "Write the text alternative for this chart."
    {"type": "input_image", "image_url": image_data_url(), "detail": "high"},  # Base64-encoded PNG
]
if source_csv is not None:  # optional: append the CSV after the image
    content.append({"type": "input_text",
                    "text": "Source data used to draw this chart (CSV, values in percent):\n\n" + source_csv})

response = client.responses.parse(
    model=model,  # "gpt-6.2-sol" or "gpt-6.2-astra"
    input=[{"role": "developer", "content": DEVELOPER_PROMPT},  # shared instructions come first
           {"role": "user", "content": content}],
    reasoning={"effort": "medium"},
    text_format=ChartDescription,
    max_output_tokens=25_000,
    store=False,
)

max_output_tokens=25_000 leaves plenty of room for output and reasoning without billing you upfront (you pay for input, cache activity, and generated output), while store=False tells OpenAI not to store response state. The full helper checks for incomplete replies, refusals, and API errors. Here is the shared developer prompt:

You write text alternatives for charts on LearnFlow course pages. Some readers use screen readers.

Return four fields:
- alt_text: one sentence of at most 200 characters that identifies the chart: its type, subject, and time span. Do not list values in it.
- long_description: one or two paragraphs for a reader who cannot see the chart. Cover the scales, values, relationships, and trends the chart shows, and anything a sighted reader would notice.
- claims: every factual statement in long_description, one per item. Fill track, week, and value_percent when a claim is about one track's value in one week; otherwise set them to null.
- uncertainties: anything you could not determine or had to estimate.

Rules:
- Describe only what the chart and any data you are given show. Do not explain why the numbers changed.
- When you read a value from the image instead of from supplied data, say it is approximate.
- Use percentage points for the difference between two percentages.

The prompt never hints at the missing week, the 50% floor, or the crossover, so you can reuse this same structure on other charts without giving answers away.

Define structured chart outputs with Pydantic

Structured Outputs return typed fields your code can read directly instead of parsing plain text. Valid JSON only confirms the fields match your schema; a wrong number still passes validation, so Python still checks each claim against the CSV.

Define the expected fields with Pydantic (a Python library that validates data shapes) and pass the class to text_format:

from typing import Literal
from pydantic import BaseModel


class Claim(BaseModel):
    statement: str
    track: Literal["Python", "SQL", "Power BI"] | None
    week: int | None
    value_percent: float | None


class ChartDescription(BaseModel):
    alt_text: str
    long_description: str
    claims: list[Claim]
    uncertainties: list[str]

OpenAI guarantees the schema only on completed, non-refusal responses, so check status and refusals before reading output_parsed.

Call both models, verify claims, and calculate cost

Load .env first (load_dotenv() puts OPENAI_API_KEY into the environment so OpenAI() finds it), call describe_chart() for both models, and check each structured claim against the CSV:

from dotenv import load_dotenv
from openai import OpenAI
import pandas as pd

from checker import judge_value
from describe import describe_chart

load_dotenv()  # loads OPENAI_API_KEY from .env into the environment
client = OpenAI()
df = pd.read_csv("data/learnflow_completion.csv")

for model in ("gpt-6.2-sol", "gpt-6.2-astra"):
    record = describe_chart(client, model)
    print(model, record["status"])
    if record["status"] != "completed" or not record.get("parsed"):
        print("  No completed description to evaluate.")
        continue
    print(f"  API cost: ${record['usage']['cost_usd']:.4f}")
    for claim in record["parsed"]["claims"]:
        if (
            claim["track"] is not None
            and claim["week"] is not None
            and claim["value_percent"] is not None
        ):
            verdict = judge_value(df, claim["track"], claim["week"], claim["value_percent"])
            print(" ", claim["track"], claim["week"], claim["value_percent"], "->", verdict)

Inside the repository's checker, judge_value() maps each track to its CSV column, marks out-of-range weeks as not_checkable, flags invented values for blank cells (NaN), and allows a 2-point visual margin. The helper also prices each response from response.usage using Standard rates.

To run the full four-setup comparison locally, verify the chart and CSV hashes first, then execute the comparison script:

python checker.py
python describe.py --runs 3

The second command saves your fresh outputs to a separate file so the reference outputs in the repository stay intact.

Analyze Charts From Images Alone With the GPT-6.2 Sol and Astra APIs

Given only the PNG image, both GPT-6.2 Sol and GPT-6.2 Astra described the LearnFlow chart accurately across repeated calls. Here is one of Sol's descriptions:

The horizontal axis shows enrollment cohort weeks 1–12. The vertical axis shows the percentage of each cohort that completed its course within 30 days, from 50% to 90% in 5-percentage-point steps. The lines are labeled at their right ends: Python has blue circles, SQL has orange squares, and Power BI has green triangles.

Python starts at about 72% in week 1, reaches a high of about 78% across weeks 7–9, and ends at about 76% in week 12. SQL rises at every plotted point, from about 58% in week 1 to about 81% in week 12, with a gap at week 8. SQL starts below both other tracks, moves ahead of Power BI between weeks 4 and 5, and passes Python between weeks 10 and 11. Power BI fluctuates but trends downward, from about 66% in week 1 to about 60% in week 12. By week 12, SQL leads Python by about 5 percentage points and Power BI by about 21 percentage points.

Astra was just as accurate. It opened with a warning that plotted rates are approximate, then nailed the exact whole numbers anyway.

What the image-only descriptions caught and missed

Every image-only description handled all three traps: the missing SQL point at week 8, SQL passing Python in week 11 (or between weeks 10 and 11), and the 50% to 90% axis. Both models also caught SQL passing Power BI between weeks 4 and 5 unprompted.

I was surprised that both models read every point accurately from pixels alone. Even so, every reply noted the 50% floor without explaining its visual effect: a 5-point gap fills an eighth of a 40-point axis instead of a twentieth of a 0% to 100% scale.

Add Source CSV Data to Your Chart Prompts

Because both models already scored 8 of 8 from the image alone, the factual rubric had no room to show further improvement. Including the CSV as text still made the descriptions more precise by replacing estimated values with exact figures. Appending the CSV added only about 120 input tokens and passed the blank week 8 cell explicitly:

week,python_pct,sql_pct,power_bi_pct
7,78,70,63
8,78,,62
9,78,74,63

What changed was the wording. From pixels alone, both models hedged with "about" and listed pixel estimation as uncertain. With the CSV, they dropped the hedges and wrote exact figures, and they still caught the 50% floor from the image.

Skipping the CSV works on a simple three-line chart with whole numbers, though denser charts are a different story. Earlier work in the MatplotAlt paper studied automated Matplotlib alt text and showed that supplying chart data helped GPT-4 Turbo reduce factual errors. Here we measure GPT-6.2 Sol and Astra specifically and separate factual accuracy from publication readiness, showing where passing numeric checks still leaves editorial work.

GPT-6.2 Sol vs. Astra: Accuracy, Accessibility, and Cost

All four setups ran on November 18, 2026 (Python 3.13, openai 3.55.1) with 3 independent calls each at medium effort, detail: "high", and Standard rates. Python checked structured track-week-value claims against the CSV; one human reviewer confirmed all 8 facts and judged readiness to publish (noting the 50% floor was in the factual rubric, while explaining its visual effect was part of publication review):

Setup

Factual pass (reviewed)

Ready without edits (reviewed)

Required facts

Unsupported claims

Median time

Output tokens (mean)

Reported reasoning tokens (mean)

Mean API cost per response

Sol, image only

3 of 3

0 of 3

8 of 8

0

15.7 s

1,443

78

$0.0158

Astra, image only

3 of 3

0 of 3

8 of 8

0

15.2 s

1,090

0

$0.0490

Sol, image + CSV

3 of 3

0 of 3

8 of 8

0

17.3 s

1,455

158

$0.0160

Astra, image + CSV

3 of 3

0 of 3

8 of 8

0

14.5 s

981

0

$0.0451

Response times bounced between 12.7 and 22.7 seconds with no clear pattern. Sol spent reasoning tokens (extra thinking tokens billed as output), while Astra reported 0 across these calls.

Accuracy, publication readiness, and checker limits

Both models tied on factual accuracy: all 12 replies passed the 8-fact rubric after human review with 0 unsupported claims. None was ready to publish without edits, as judged by one human reviewer for visual context and clarity (we did not conduct a screen-reader user study).

Every reply omitted the 50% axis effect, and one Sol draft listed all 35 available data points in prose. I almost left that draft alone because every number matched the CSV, then read it aloud and saw why long number lists belong in an HTML table. Astra wrote shorter prose overall (135 to 175 words versus Sol's 154 to 182).

Python could not catch every nuance on its own either. Its pattern-matching (regex) prose checks missed some phrasing variations and twice flagged valid sentences (pairing 58% with week 7, and treating "breaks at week 8 because no value is shown" as a causal claim). Treat code checks as a first filter, then read flagged lines yourself.

Cost breakdown and prompt caching savings

Because every response passed factually, the mean costs above reflect the API cost per structured response (alt text, long description, claims, and uncertainties) across three repeated calls per setup. Single-call workloads with less prompt reuse will see slightly different totals.

On image-only calls, Astra cost about 3.1 times Sol ($0.0490 versus $0.0158) despite 4x token rates, because output length, reasoning tokens, and cache reuse all shape the bill. Calculate cost from response.usage instead of list prices alone.

Prompt caching lowers repeat input costs when the prompt opening matches across calls, so check the cached token fields in response.usage instead of assuming a hit. On Astra image-only calls, cost fell from $0.0570 on the first call to around $0.045 later, with both cache reuse and output length contributing.

Publish Accessible Chart Descriptions in HTML

Pair a short alt attribute, a visible long description, and an HTML data table inside one <figure> element (the W3C complex-images pattern). The excerpt below shows the layout; the repository's HTML builder generates all 12 rows and escapes model text safely so it cannot break the page markup:

<figure role="group">
  <img src="learnflow_chart.png"
       alt="Line chart of LearnFlow's 30-day course completion rates for Python, SQL, and Power BI across enrollment cohort weeks 1 to 12. Description and data table below.">
  <figcaption>
    <h2>Chart description</h2>
    <p>...reviewed long description...</p>
    <table>
      <caption>Share of each weekly enrollment cohort that completed its course within 30 days</caption>
      <thead><tr><th scope="col">Cohort</th><th scope="col">Python</th><th scope="col">SQL</th><th scope="col">Power BI</th></tr></thead>
      <tbody>
        <tr><th scope="row">Week 8</th><td>78%</td><td>No data</td><td>62%</td></tr>
        <!-- 11 more rows -->
      </tbody>
    </table>
  </figcaption>
</figure>

Label missing cells as "No data" instead of leaving them blank so screen readers announce the gap clearly. Starting from one of Sol's image-only drafts, I made four quick edits before publishing:

  • Removed the "about" hedges once every number matched the CSV
  • Added the exact 23-percentage-point gain for SQL
  • Stated plainly that week 8 has no recorded value
  • Added a sentence explaining that the 50% axis floor makes gaps between lines look wider

The axis note explains how the chart's scale affects the visual comparison, while the data table gives every reader access to the exact numbers.

Web page titled LearnFlow course completion by weekly cohort, showing the LearnFlow line chart, a Chart description heading with two paragraphs of reviewed text, and a data table with columns Cohort, Python, SQL, and Power BI for weeks 1 to 12, where the SQL cell for week 8 reads No data.

Reviewed description beside the same chart. Image by Author.

See our dashboard design tutorial for a wider accessibility checklist. Treat this page as a reviewed accessibility aid; full Web Content Accessibility Guidelines (WCAG) conformance requires a broader audit.

To generate the complete HTML page locally from the reviewed description and CSV:

python publish_page.py

The command writes reviewed_page.html next to the chart PNG so you can open it straight in a browser.

Explore the outputs in Streamlit

In the video, I open the Streamlit web viewer in the repository, step through the chart and source data, inspect the flagged Sol output where human review cleared the regex alarm, and compare token costs across all four setups.

The Streamlit app walks through every output. Video by Author.

Final Thoughts

On LearnFlow, both GPT-6.2 Sol and GPT-6.2 Astra passed our factual checks after human review, yet none of the 12 outputs was ready to publish without edits. Sol cost roughly a third of Astra's price on this clean chart ($0.0158 versus $0.0490 per image-only response), while attaching the CSV sharpened numeric wording without changing factual scores.

I would start with GPT-6.2 Sol on clean, well-labeled charts, attach the source CSV whenever exact figures go straight to a web page, and keep a brief human review for visual context like a 50% axis floor. Test GPT-6.2 Astra on denser dashboards with decimals like 73.4% or dozens of overlapping lines before switching models there. More than anything, treat factual accuracy and accessibility quality as separate checks.

For API basics, our Working with the OpenAI API course covers the core Python workflow.

Khalid Abdelaty

Författare

Khalid Abdelaty

I’m a data engineer and community builder who works across data pipelines, cloud, and AI tooling while writing practical, high-impact tutorials for DataCamp and emerging developers.

FAQs

Can GPT-6.2 generate accessible chart descriptions without human review?

In this experiment, neither model produced a description we considered ready to publish without edits. Both GPT-6.2 Sol and Astra cleared every factual check after human review, yet every reply omitted the editorial context on how the 50% axis floor affects visual gaps, and one Sol draft listed all 35 available values in prose. Use the model for a fast first draft backed by Python numeric checks, followed by a brief human edit.

How do I access the GPT-6.2 Sol and Astra API in Python?

Create an OpenAI API key, install openai 3.53.0 or newer, and pass gpt-6.2-sol or gpt-6.2-astra to client.responses.create() or client.responses.parse(). Both models accept PNG, JPEG, WEBP, and non-animated GIF images (up to 512 MB per request) via URL, Base64, or a Files API file ID. Chat Completions works for text and images too, though tool calling requires the Responses API.

Why does a GPT-6.2 API request fail with temperature or reasoning.effort="none"?

GPT-6.2 rejects reasoning.effort="none" (use low when migrating from none or minimal, or medium for new work). Omit temperature, top_p, and top_logprobs on the Responses API, and omit logprobs as well on Chat Completions.

Can I use Batch processing or background windows with GPT-6.2 to cut costs?

Yes, if you can wait for turnaround. The Batch API cuts costs to 50% of Standard rates for both models, which fits overnight chart jobs well. For faster turnaround, Responses API background windows (in public beta) offer 30% off for a 2-hour window and 40% off for an 8-hour window.

Does setting store=False stop OpenAI from keeping chart images?

Setting store=False stops the Responses API from storing response state (otherwise kept for at least 30 days). OpenAI still keeps abuse monitoring logs for up to 30 days unless your organization has Zero Data Retention or Modified Abuse Monitoring. Check OpenAI's data controls guide for eligibility and image-scanning rules before sending sensitive charts.

Ämnen

Relaterat