We use cookies to enhance your experience on the site
CodeWorlds
Back to collections
Guide16 min read

OpenAI - A complete guide to the AI platform that changed the tech world

OpenAI models, their prices and context windows, the Responses API, the Agents SDK, and ways to cut costs. A guide to the platform from the integration side.

OpenAI - A complete guide to the AI platform that changed the tech world

In November 2022, OpenAI released ChatGPT and within 5 days, over a million users signed up. Today the company is valued at 852 billion dollars, and its products from GPT-5 through DALL-E to Sora set the direction for the industry. For a developer, though, OpenAI is above all an API platform with models, tools, and libraries to build your own applications on.

What is OpenAI?

OpenAI is an American AI research and technology company founded in December 2015 by Sam Altman, Elon Musk, Ilya Sutskever, Greg Brockman, and others. It initially operated as a non-profit organization with the mission of developing "safe and beneficial" artificial general intelligence (AGI).

Since 2019, OpenAI has undergone a structural transformation - from a pure non-profit to a hybrid "capped profit" model, and in 2025, it transformed into a public benefit corporation (PBC) under the oversight of the OpenAI Foundation. This evolution was driven by a simple fact: AI development requires enormous computational and financial resources.

The company is headquartered in San Francisco. Its CEO is Sam Altman, and the company employs thousands of workers and researchers.

History and key moments

2015-2018: The beginning

OpenAI was founded with a $1 billion pledge from Altman, Musk, Reid Hoffman, Peter Thiel, AWS, and others. The goal was to conduct open AI research, hence the "Open" in the name. In 2018, Elon Musk left the board after an unsuccessful attempt to take control of the organization.

2019-2022: GPT and the breakthrough

In 2019, GPT-2 was created, surprising everyone with the quality of generated text. GPT-3 (2020) with 175 billion parameters launched the era of large language models. In 2021, DALL-E (image generation) and Codex (code generation) appeared. GPT-3.5 and ChatGPT (November 2022) triggered the global AI boom.

2023: Turbulence and GPT-4

In March 2023, OpenAI released GPT-4 - a multimodal model understanding text and images. In November, the board removed Sam Altman as CEO. Five days later, he returned after practically all employees threatened to leave. The crisis led to a board restructuring.

2024-2025: Reasoning models and GPT-5

OpenAI introduced the o1/o3/o4-mini model series with "thinking" - models can reason step by step before providing an answer. In 2025, GPT-5 appeared, unifying general intelligence, reasoning, coding, and multimodality in one model family. Also released were Sora 2 (video), Operator (web agent), ChatGPT Atlas (browser), and GPT-OSS (open-weight models).

In May 2025, OpenAI acquired for $6.5 billion the company IO founded by Jony Ive (former Apple design chief), planning to create a new category of personal devices.

On 31 March 2026 the company closed a funding round of 122 billion dollars, taking its valuation to 852 billion. Amazon took the largest share alongside Nvidia and SoftBank, and part of the round was opened to individual investors. At those sums it is worth remembering that a valuation says nothing about the stability of the API price list, which changed several times over the same period.

OpenAI products

ChatGPT

OpenAI's flagship consumer product. A chat interface for interacting with GPT models:

  • ChatGPT Free - free access to GPT-4o mini
  • ChatGPT Plus ($20/mo) - GPT-4o, GPT-5, DALL-E, data analysis
  • ChatGPT Pro ($200/mo) - unlimited access to all models, o1-pro, deep research
  • ChatGPT Team ($25/person/mo) - team version
  • ChatGPT Enterprise - corporate version with compliance and SSO

DALL-E / gpt-image

Image generation models from text descriptions. DALL-E 3 integrated with ChatGPT. In 2025, OpenAI transitioned to gpt-image models based on GPT's multimodal capabilities, replacing earlier diffusion models.

Sora

A text-to-video model generating videos up to 1920x1080 resolution. Sora 2 (2025) offers improved physics simulation and synchronized audio.

Whisper

A speech recognition model - audio-to-text transcription with multi-language support (including Polish). Open-source, also available via API.

Operator

An AI agent for automating browser tasks - logging in, filling forms, navigating websites.

OpenAI models for developers

GPT-5 family

ModelInput/1M tokensOutput/1M tokensContextPurpose
gpt-5.6-sol$5.00$30.001.05MFlagship, hardest tasks
gpt-5.6-terra$2.00$12.001.05MBalance of quality and price
gpt-5.6-luna$0.20$1.201.05MCost optimised variant
gpt-5.5$5.00$30.00-Previous flagship generation
gpt-5.4$2.50$15.00-Previous mid generation
gpt-5$1.25$10.00-General model with reasoning
gpt-5-mini$0.25$2.00-Cost and performance balance
gpt-5-nano$0.05$0.40-Minimum costs

All three models in the 5.6 line share the same 1.05 million token context and a 128 thousand token output limit, differing in capability level and price. A dash in the context column means the documentation states that value only for the current line, so for older models check it directly in the model description.

GPT-4 family

ModelInput/1M tokensOutput/1M tokensContextPurpose
GPT-4o$2.50$10.00128KVersatile flagship
GPT-4o Mini$0.15$0.60128KFast and cheap
GPT-4.1$2.00$8.001MCoding, instructions
GPT-4.1 Mini$0.40$1.601MCheap with 1M context
GPT-4.1 Nano$0.10$0.401MFastest

Reasoning models (O-series)

ModelInput/1M tokensOutput/1M tokensContextPurpose
o1$15.00$60.00200KDeep reasoning
o3$2.00$8.00200KNext-gen reasoning
o3-mini$1.10$4.40200KFast reasoning

O-series models consume "reasoning tokens" for internal thinking - these tokens are billed as output but not visible in the API response. A response with 500 visible tokens might consume 2000+ tokens.

Specialist models

  • gpt-image-1.5 - image generation
  • gpt-4o-transcribe / whisper-1 - audio transcription
  • gpt-4o-mini-tts - text-to-speech
  • text-embedding-3-small/large - text embeddings

How to choose a model?

  • Prototyping: GPT-5 Nano or GPT-4o Mini (cheapest)
  • General applications: GPT-4o or GPT-5
  • Complex reasoning: gpt-5.6-sol or o3
  • Coding: GPT-4.1 (optimized for instructions)
  • Batch processing: GPT-4o Mini + Batch API (50% cheaper)

Responses API

The Responses API is OpenAI's newest API, combining the simplicity of Chat Completions with the built-in tools of the Assistants API. It replaces the earlier Assistants API (deprecated, removal in August 2026).

Basic usage

Code
Python
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-4o",
    input="Explain what React is in 3 sentences"
)
print(response.output_text)

With built-in tools

Code
Python
response = client.responses.create(
    model="gpt-4o",
    tools=[{"type": "web_search_preview"}],
    input="What are the latest changes in Next.js 15?"
)
print(response.output_text)

Streaming

Code
Python
stream = client.responses.create(
    model="gpt-4o",
    input="Write a tutorial about TypeScript generics",
    stream=True
)
for event in stream:
    if hasattr(event, "delta"):
        print(event.delta, end="", flush=True)

Chat Completions API

The classic API for generating responses in conversation format:

Code
Python
from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful programming assistant."},
        {"role": "user", "content": "How do I create a custom hook in React?"}
    ]
)
print(response.choices[0].message.content)

Structured Outputs

Forcing responses in a defined JSON schema:

Code
Python
from pydantic import BaseModel

class CodeReview(BaseModel):
    issues: list[str]
    suggestions: list[str]
    score: int

response = client.beta.chat.completions.parse(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "Analyze the code and return a review."},
        {"role": "user", "content": "function add(a,b){return a+b}"}
    ],
    response_format=CodeReview
)
review = response.choices[0].message.parsed
print(f"Score: {review.score}")
print(f"Issues: {review.issues}")

Function calling

Allows the model to invoke external functions:

Code
Python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What's the weather in Warsaw?"}],
    tools=tools,
    tool_choice="auto"
)

tool_call = response.choices[0].message.tool_calls[0]
print(f"Function: {tool_call.function.name}")
print(f"Args: {tool_call.function.arguments}")

Vision (image analysis)

Code
Python
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What do you see in this screenshot?"},
                {"type": "image_url", "image_url": {"url": "https://example.com/screenshot.png"}}
            ]
        }
    ]
)
print(response.choices[0].message.content)

Embeddings

Embeddings convert text into numerical vectors that reflect semantic meaning. Similar texts generate similar vectors.

Code
Python
response = client.embeddings.create(
    model="text-embedding-3-small",
    input="TypeScript is a superset of JavaScript with static types"
)
embedding = response.data[0].embedding
print(f"Dimensions: {len(embedding)}")

Embedding use cases

  • Semantic search - finding documents by meaning, not keywords
  • RAG (Retrieval-Augmented Generation) - providing context to models
  • Classification - categorizing texts
  • Recommendations - suggesting similar content
  • Anomaly detection - identifying unusual patterns

Embedding model comparison

ModelDimensionsPrice/1M tokensUse case
text-embedding-3-small1536$0.02Most applications
text-embedding-3-large3072$0.13Maximum quality

For most applications, text-embedding-3-small offers sufficient quality at 1/6th the cost of the large version.

Agents SDK

The Agents SDK is OpenAI's framework for building AI agents - programs that can autonomously execute multi-step tasks, using tools and delegating work to other agents.

Basic agent (Python)

Code
Python
from agents import Agent, Runner

agent = Agent(
    name="code-reviewer",
    instructions="You are an expert code reviewer. Analyze code for bugs, security issues, and performance problems.",
    model="gpt-4o"
)

result = Runner.run_sync(agent, "Review this function: def add(a,b): return a+b")
print(result.final_output)

Agent with tools

Code
Python
from agents import Agent, Runner, function_tool

@function_tool
def search_docs(query: str) -> str:
    """Search project documentation"""
    return f"Found documentation about: {query}"

@function_tool
def run_tests(file_path: str) -> str:
    """Run tests for a specific file"""
    return f"All tests passed for {file_path}"

agent = Agent(
    name="dev-assistant",
    instructions="Help developers by searching docs and running tests.",
    tools=[search_docs, run_tests],
    model="gpt-4o"
)

result = Runner.run_sync(agent, "Check if the auth module has documentation and run its tests")
print(result.final_output)

Agents SDK (TypeScript)

Code
TypeScript
import { Agent, run } from "@openai/agents"

const agent = new Agent({
  name: "assistant",
  instructions: "You are a helpful coding assistant.",
  model: "gpt-4o",
})

const result = await run(agent, "Explain React hooks")
console.log(result.finalOutput)

Handoffs (delegation)

Agents can delegate tasks to other agents:

Code
Python
from agents import Agent, Runner

researcher = Agent(
    name="researcher",
    instructions="Research topics thoroughly and provide detailed findings."
)

writer = Agent(
    name="writer",
    instructions="Write clear, engaging content based on research.",
    handoffs=[researcher]
)

result = Runner.run_sync(writer, "Write an article about WebAssembly")
print(result.final_output)

Built-in tools

  • web_search - internet search
  • file_search - document search
  • code_interpreter - Python code execution
  • image_generation - image creation
  • computer_use - interface automation

Codex CLI

An open-source tool for agent-style coding in the terminal:

Code
Bash
npx @openai/codex "Add error handling to the auth module"

Codex works directly with your repository - reads files, proposes changes, lets you review and accept them. It integrates with the Agents SDK via MCP (Model Context Protocol).

Cost optimization

Prompt caching

OpenAI automatically caches repeated prompt prefixes:

Model familySavings
GPT-590% on cached tokens
GPT-4.175%
GPT-4o / O-series50%

Batch API

For tasks that don't require immediate responses (data analysis, content generation):

Code
Python
batch = client.batches.create(
    input_file_id="file-abc123",
    endpoint="/v1/chat/completions",
    completion_window="24h"
)

The Batch API processes requests within 24 hours at a 50% discount.

Cascade architecture

An efficient strategy is routing requests through models of increasing power:

  1. GPT-4o Mini handles 80% of simple queries ($0.15/1M input)
  2. GPT-4o handles 15% of medium queries ($2.50/1M input)
  3. o3 handles 5% of complex queries ($2.00/1M input + reasoning)

Fine-tuning

Training a model on your own data:

Code
Python
file = client.files.create(
    file=open("training_data.jsonl", "rb"),
    purpose="fine-tune"
)

job = client.fine_tuning.jobs.create(
    training_file=file.id,
    model="gpt-4.1-2025-04-14"
)

Fine-tuning is available for GPT-4.1, GPT-4o, and o4-mini. Training cost: $1.50-$100/h depending on the model.

SDKs and libraries

Python

Code
Bash
pip install openai
Code
Python
from openai import OpenAI

client = OpenAI()  # automatically reads OPENAI_API_KEY from env

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello!"}]
)

Node.js / TypeScript

Code
Bash
npm install openai
Code
TypeScript
import OpenAI from "openai"

const client = new OpenAI()

const response = await client.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello!" }],
})
console.log(response.choices[0].message.content)

.NET

Code
Bash
dotnet add package OpenAI

REST API (curl)

Code
Bash
curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [{"role": "user", "content": "Hello!"}]
  }'

Audio API

Transcription (Speech-to-Text)

Code
Python
audio_file = open("meeting.mp3", "rb")
transcript = client.audio.transcriptions.create(
    model="gpt-4o-transcribe",
    file=audio_file
)
print(transcript.text)

Text-to-Speech

Code
Python
response = client.audio.speech.create(
    model="gpt-4o-mini-tts",
    voice="alloy",
    input="TypeScript is a superset of JavaScript."
)
response.stream_to_file("output.mp3")

Image generation

Code
Python
response = client.images.generate(
    model="gpt-image-1",
    prompt="A futuristic city with flying cars, cyberpunk style",
    size="1024x1024",
    n=1
)
print(response.data[0].url)

Security and privacy

API data policy

  • Data sent via API is not used for model training (by default)
  • OpenAI retains API data for 30 days for abuse monitoring
  • Zero Data Retention (ZDR) available for qualifying customers
  • SOC 2 Type II compliance

Rate limits

Limits depend on user Tier (Tier 1-5), which increases with spending:

TierRequirementsRPM (GPT-4o)TPM (GPT-4o)
Tier 1$5 deposit50030,000
Tier 2$50 spent5,000450,000
Tier 3$100 spent5,000800,000
Tier 5$1,000 spent10,00030,000,000

API keys

Code
Bash
export OPENAI_API_KEY="sk-..."

Never commit API keys to your repository. Use environment variables or secret managers.

Comparison with competitors

FeatureOpenAIAnthropicGoogle (Gemini)Meta (Llama)
Best modelgpt-5.6-solClaude Opus 5Gemini 2.5 ProLlama 3.3 70B
Input price per 1Mfrom $0.05from $1.00see pricing pageFree locally
Flagship context1.05M1M2M128K
Image analysisYesYesYesYes (Vision variants)
AgentsAgents SDKAgent SDKVertex AI AgentsNo official
Open-weight modelsGPT-OSS (Apache 2)NoGemma (Apache 2)Yes (Llama License)
Fine-tuningYesNoYesYes (locally)

The table shows the state at publication and ages faster than anything else in this text. Input prices refer to the cheapest model in each vendor's lineup rather than the one in the first row. Before making a budget decision, check the rates directly with the vendor, since in this industry they change on a monthly rather than yearly cycle.

A practical note on choosing: public benchmarks measure tasks that rarely resemble yours. Build a thin layer with one call interface and compare two vendors on your own data. That is the only test that tells you anything. If data cannot leave the company, add a model run locally through Ollama to the comparison, and when building multi step flows, LangChain normalises the interface.

Practical use cases

Chatbot with context

Code
Python
messages = [
    {"role": "system", "content": "You are an online store assistant. Respond helpfully."},
    {"role": "user", "content": "I'm looking for running shoes in size 10"}
]

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages
)

messages.append(response.choices[0].message)
messages.append({"role": "user", "content": "What about waterproof models?"})

response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages
)

Document analysis with RAG

Code
Python
from openai import OpenAI
import numpy as np

client = OpenAI()

def get_embedding(text):
    response = client.embeddings.create(
        model="text-embedding-3-small",
        input=text
    )
    return response.data[0].embedding

def cosine_similarity(a, b):
    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))

docs = ["React is a library for building UI", "Next.js is a React framework with SSR"]
doc_embeddings = [get_embedding(d) for d in docs]

query_embedding = get_embedding("How to render on the server side?")
similarities = [cosine_similarity(query_embedding, de) for de in doc_embeddings]
best_doc = docs[np.argmax(similarities)]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": f"Answer based on: {best_doc}"},
        {"role": "user", "content": "How to render on the server side?"}
    ]
)

Content moderation

Code
Python
response = client.moderations.create(
    model="omni-moderation-latest",
    input="Check this content for violations"
)
print(response.results[0].flagged)

FAQ

How much does using the OpenAI API cost?

Charges are based on tokens (text fragments). The cheapest model (GPT-4.1 Nano) costs $0.10/1M input tokens. New accounts receive free credits to get started.

How do GPT models differ from O models?

GPT models (GPT-4o, GPT-5) are general-purpose models - fast and versatile. O models (o1, o3) are reasoning models - they "think" before answering, better at complex logical and mathematical problems, but slower and more expensive.

Can I fine-tune OpenAI models?

Yes, fine-tuning is available for GPT-4.1, GPT-4o, and o4-mini. You need training data in JSONL format.

Is data sent to the API secure?

API data is not used for model training by default. OpenAI retains it for 30 days for monitoring. For sensitive data, Zero Data Retention is available.

How to choose between OpenAI and alternatives?

OpenAI has the broadest developer tool ecosystem and the best reasoning models. Anthropic (Claude) excels in safety and long context. Google (Gemini) offers the longest context (2M) and GCP integration. Meta (Llama) has the best open-source models for self-hosting.

Does OpenAI have open-source models?

Yes, GPT-OSS (gpt-oss-120b and gpt-oss-20b) were released in August 2025 under the Apache 2.0 license.

What is Responses API vs Chat Completions?

The Responses API is the newer API with built-in tools (web search, file search, code interpreter). Chat Completions is the older, simpler API. OpenAI recommends the Responses API for new projects.

Are ChatGPT and the API the same thing?

No. ChatGPT is a consumer product (chat application). The API is a service for developers to integrate models into their own applications. They have separate pricing plans.

Summary

OpenAI is the leader in artificial intelligence, offering the broadest developer tool ecosystem - from language and vision models, through SDKs for building agents, to fine-tuning and embedding tools.

For developers, the key offerings are: the Responses API as the main entry point, the Agents SDK for building multi-step workflows, Structured Outputs for typed output, function calling for external service integration, and a rich model library from the cheapest (GPT-4.1 Nano) to the most powerful (o3, gpt-5.6-sol).

Whether you're building a chatbot, RAG system, AI agent, or data processing pipeline - the OpenAI platform provides tools for virtually any AI task.

One thing here is worth remembering above all the details: model names and rates change on this platform faster than the content of any guide. The current model list sits in the OpenAI documentation, and current prices on the pricing page. Before hard coding a model identifier, check those two addresses.