The Complete ChatGPT Guide
GPT-4o, API & automation
From the basics to full mastery: Prompt Engineering, Custom GPTs, the OpenAI API and Function Calling — with detailed code examples.
What is ChatGPT?
ChatGPT is a conversational interface from OpenAI, running on the GPT (Generative Pre-trained Transformer) family of models. It is not just "AI that answers questions" — it is a full platform for writing, analysis, coding, image and voice generation, building apps and automation. Since its launch in November 2022 it has changed how millions of people work around the world.
At the heart of the product is a large language model (LLM) trained on enormous amounts of text and finished with RLHF (Reinforcement Learning from Human Feedback) — a technique that makes it useful, safe and helpful.
GPT-4o vs the o-series models vs GPT-3.5 — what is the difference?
| Model | Context | Vision | Price (1M input) | Recommended for |
|---|---|---|---|---|
| GPT-4o | 128K | Yes | $2.50 | Any general use, default |
| GPT-4o mini | 128K | Yes | $0.15 | High volume, low cost |
| o3 | 200K | Yes | $10.00 | reasoning, math, complex code |
| o4-mini | 200K | Yes | $1.10 | reasoning at a reasonable price |
| GPT-3.5 Turbo | 16K | No | $0.50 | legacy — not recommended for new projects |
What can you do with ChatGPT?
- Writing: articles, emails, copywriting, scripts, translation, editing
- Code: writing, debug, code review, code explanation, converting programming languages
- Data analysis: Code Interpreter runs Python directly, creates charts and analyzes files
- Images: Built-in DALL-E 3 — generation and editing from text
- Voice: Voice Mode with low latency like a real human conversation
- Research: Real-time Web Search with source Grounding (ChatGPT Plus)
- Automation: Function Calling, Assistants API, multi-step Agents
Free — GPT-4o with rate limits, limited DALL-E. Plus ($20/month) — full access to GPT-4o, o3, o4-mini, DALL-E 3, Web Search, Code Interpreter, Custom GPTs. Team ($30/user) — data privacy, longer context, organizational management. Enterprise — SSO, audit logs, a guaranteed SLA.
The roadmap to mastering ChatGPT
The journey from "beginner" to "master" goes through 5 clear stages. Each stage builds on the previous one — don't skip.
Prompt Engineering
Prompt Engineering is the art of phrasing instructions that get the best result out of the model. The difference between a bad prompt and a good one can be the difference between useless output and output that saves hours of work. It is not magic — it is a learnable skill.
Zero-shot vs Few-shot vs Chain-of-Thought
A direct question with no examples. Works well for simple, clear tasks.
Hello world"
A few examples before the request. Trains the model on the desired format.
Negative → 😞
Neutral → 😐
Classify: 'I loved it!'"
Ask the model to think out loud. Improves reasoning, math and logic.
Show your reasoning
before the answer."
Persona Technique — "Act as..."
One of the most powerful techniques is defining a persona — ask the model to act as an expert in a specific field. This significantly improves the quality, depth and style of the output. Here is a ready-to-use template:
SYSTEM: Act as an expert in [field] with [X] years of experience.
Your style: [professional/friendly/technical].
The user: [audience description].
Output format: [JSON/Markdown/lists].
Language: clear language, technical terms in English.
If you are not sure — say so explicitly. Do not make up information.
Structured Output — JSON Mode
When you need structured output for code processing, there are two approaches: defining response_format: { type: "json_object" } in the API, or usingStructured Outputs — defining a precise JSON Schema the model must comply with. Structured Outputs guarantees 100% compliance with the schema.
from openai import OpenAI
from pydantic import BaseModel
client = OpenAI()
class ArticleAnalysis(BaseModel):
title: str
main_topic: str
sentiment: str # "positive" | "negative" | "neutral"
key_points: list[str]
word_count: int
response = client.beta.chat.completions.parse(
model="gpt-4o",
messages=[
{"role": "system", "content": "Analyze the article and provide structured JSON."},
{"role": "user", "content": "Article: [article text here]"}
],
response_format=ArticleAnalysis,
)
analysis = response.choices[0].message.parsed
print(f"Topic: {analysis.main_topic}")
print(f"Key points: {analysis.key_points}")
Temperature & Top-p — controlling variety
Defines the pool of words the model chooses from. 0.1 = only the most probable words (less variety, more consistency). 0.9 = a wider variety.
Recommendation: Change only Temperature. Do not change both Top-p and Temperature together — they interact and create unpredictable results.
- ✗ A prompt that is too long and unfocused — break it into separate steps, send focused instructions
- ✗ Not specifying the desired output format — always define: list/JSON/paragraph/table
- ✗ Asking to "be creative" without constraints — this yields generic results
- ✗ Lack of context — "write an article" vs "write a LinkedIn article about AI for a B2B manager audience"
- ✗ Not verifying the output — ChatGPT may make up information. Always verify critical facts
GPT-4o capabilities
GPT-4o ("omni") is OpenAI's multimodal model — it understands and generates text, images and voice in one continuous conversation. This is a significant leap from earlier models that handled each modality separately with high latency.
Vision — analyzing images and documents
Send any image, screenshot, PDF, diagram or chart — GPT-4o will describe, analyze and answer questions about it. The interface supports URLs and local files (base64). Main uses at work:
- analyzing business charts and graphs — trends, anomalies, comparisons
- reading forms, receipts, invoices and Word/PDF documents
- Debugging UI screenshots — spotting errors in interfaces
- explaining architecture diagrams and ERDs
- translating images with text, scanned documents (OCR)
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "Analyze this chart: what is the overall trend? What anomalies are there?"},
{
"type": "image_url",
"image_url": {"url": "https://example.com/chart.png"}
# or: "url": f"data:image/jpeg;base64,{base64_image}"
}
]
}
]
)
print(response.choices[0].message.content)
When analyzing a complex PDF, break it into single pages (PDF to PNG images) and send one page at a time. GPT-4o handles documents up to about 20 pages directly, but quality drops on long files. Usepypdf + pdf2image in Python for automatic splitting.
DALL-E 3 — image generation
ChatGPT Plus has built-in access to DALL-E 3. Just ask "create an image of..." — GPT-4o even automatically improves your prompt before sending it to DALL-E. Through the API you can control size, quality and style:
from openai import OpenAI
client = OpenAI()
response = client.images.generate(
model="dall-e-3",
prompt="a minimalist logo for an AI company, blue and purple colors, flat design style, white background",
size="1024x1024", # 1024x1024 | 1792x1024 | 1024x1792
quality="hd", # "standard" | "hd"
style="vivid", # "vivid" | "natural"
n=1
)
print(response.data[0].url)
print(response.data[0].revised_prompt) # the prompt improved by GPT
Code Interpreter — a built-in Python engine
Code Interpreter (Advanced Data Analysis) runs Python code in real time in an isolated sandbox. Drop in a CSV, Excel or JSON file — and get analysis, charts and insights. It is a hugely valuable tool for data people, analysts and managers.
- statistical analysis: averages, outliers, trends, correlations
- visualization with matplotlib and seaborn — charts and graphs
- file processing: extracting text from PDF, editing Excel, converting formats
- complex calculators: ROI, NPV, currency conversions, financial calculations
- basic NLP analysis: word counts, sentiment, entity extraction
Voice Mode — a human conversation
GPT-4o Voice Mode enables a spoken conversation with sub-second latency — close to a natural human conversation. The model detects intonation, can be interrupted mid-sentence, and includes a variety of built-in voices. Available in ChatGPT Plus via the mobile app. Uses: language practice, one-on-one meetings, preparing speeches.
Memory — memory across conversations
ChatGPT can save facts about you across different conversations and use them in the future. You can manage the memory manually: "Remember that I am a CTO, a Python developer, and working on a SaaS project in healthcare." Memory is available in Plus and Team, and can be turned off via Settings > Personalization > Memory.
Custom GPTs
Custom GPTs let you build a personalized version of ChatGPT with specific instructions, knowledge and capabilities — without writing a single line of code. You can share them publicly in the GPT Store or keep them private for personal or organizational use.
The three components of a Custom GPT
Fixed System Prompt instructions. Define persona, behavior, limits and format. Up to ~8,000 characters. The heart of the GPT.
Upload PDF, Word, TXT — the model uses them as a knowledge base. Ideal for product documentation, an organizational FAQ, procedures, price lists.
Connecting to external APIs via an OpenAPI spec. The model calls an API, sends data, runs webhooks — all in the conversation.
Example: a Custom GPT for a project manager
# Example Instructions — Custom GPT "My Project Manager"
You are a senior project manager with 15 years of experience in Agile, Scrum and Kanban.
Your role is to help plan, track and give feedback on projects.
When a problem or a new project is described, always ask about:
- Timeline and Deadline
- team size and skills
- possible Dependencies and Blockers
- Budget constraints
Always provide:
1. a breakdown into Milestones with dates
2. a list of Risks with Impact and Mitigation
3. measurable KPIs for success
Format: Markdown with clear headers.
Language: clear, professional terms in English.
Do not provide time estimates without information about team size.
The GPT Store has millions of public Custom GPTs. Before you build one yourself — search there. Popular categories: Productivity, Research, Coding, Creative Writing, Education. A simple search: chatgpt.com/gpts
ChatGPT API for developers
The OpenAI API lets you integrate GPT capabilities directly into your applications. It is the most widely used AI API in the world — with excellent documentation, SDKs for Python, JavaScript, Go, Java and more, and a huge community.
Quick start — Python SDK
# Installation
pip install openai
# Set the API Key (recommended as an environment variable)
export OPENAI_API_KEY="sk-proj-..." # Linux/Mac
# or in a .env file with python-dotenv
from openai import OpenAI
# the SDK reads OPENAI_API_KEY automatically
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a professional assistant. Always answer clearly."},
{"role": "user", "content": "Summarize this document in 3 points: [document text]"}
],
temperature=0.7,
max_tokens=1000,
top_p=1.0,
frequency_penalty=0.0,
presence_penalty=0.0
)
# read the response
print(response.choices[0].message.content)
# token usage information
print(f"Input tokens: {response.usage.prompt_tokens}")
print(f"Output tokens: {response.usage.completion_tokens}")
print(f"Total tokens: {response.usage.total_tokens}")
Function Calling / Tool Use
Function Calling lets the model call predefined functions — GPT decides when which function to call, and returns the arguments in JSON format. This is the basis for building AI Agents that perform actions in the real world.
import json
from openai import OpenAI
client = OpenAI()
# define the tools available to the model
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for a given city and date",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name, e.g.: Tel Aviv, Jerusalem"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "search_web",
"description": "Search the web for up-to-date information",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "The search query"}
},
"required": ["query"]
}
}
}
]
messages = [{"role": "user", "content": "What's the weather in Tel Aviv today?"}]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
tool_choice="auto" # "auto" | "required" | "none"
)
# check if the model wants to call a function
choice = response.choices[0]
if choice.finish_reason == "tool_calls":
tool_call = choice.message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
print(f"Call to: {tool_call.function.name}")
print(f"Arguments: {args}")
# here you run the real function and return the result
Streaming — real-time responses
from openai import OpenAI
client = OpenAI()
# Streaming returns chunks in real time — like ChatGPT
with client.chat.completions.stream(
model="gpt-4o",
messages=[{"role": "user", "content": "Write a short poem about the Mediterranean Sea"}]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
print() # a new line at the end
Assistants API + Threads
The Assistants API is for applications that need to manage long conversations, keep history, and use tools — all managed by OpenAI. Suited to chatbots, personal assistants, and Q&A systems.
from openai import OpenAI
client = OpenAI()
# Step 1: create an Assistant (once)
assistant = client.beta.assistants.create(
name="Task management assistant",
instructions="You help manage daily tasks. Answer clearly.",
model="gpt-4o",
tools=[
{"type": "code_interpreter"},
{"type": "file_search"}
]
)
# Step 2: create a Thread per conversation
thread = client.beta.threads.create()
# Step 3: add a message to the conversation
client.beta.threads.messages.create(
thread_id=thread.id,
role="user",
content="Prioritize the tasks: writing a report, a meeting with a client, updating the README, code review"
)
# Step 4: run and wait for the result
run = client.beta.threads.runs.create_and_poll(
thread_id=thread.id,
assistant_id=assistant.id
)
# Step 5: read the response
if run.status == "completed":
messages = client.beta.threads.messages.list(thread_id=thread.id)
print(messages.data[0].content[0].text.value)
Pricing — what does it cost?
| Model | Input (1M) | Output (1M) | Note |
|---|---|---|---|
| GPT-4o | $2.50 | $10.00 | Most popular |
| GPT-4o mini | $0.15 | $0.60 | High volume |
| o3 | $10.00 | $40.00 | Complex reasoning |
| o4-mini | $1.10 | $4.40 | Budget reasoning |
| text-embedding-3-small | $0.02 | — | RAG, semantic search |
| Whisper (STT) | $0.006/min | — | Audio transcription |
- 1.Prompt Caching — a 50% discount on tokens saved in cache. Works automatically on identical prompts.
- 2.Batch API — processing large volumes at a 50% discount with a 24-hour SLA.
- 3.A precise max_tokens — set it to your actual need. Every token you don't need is a wasted cost.
5 hands-on projects
Real learning happens through building. Here are 5 projects ranked by difficulty — each with a clear scope, a realistic time, and skills you'll gain.
A Python chatbot with a CLI that answers questions from a defined FAQ, keeps history and escalates to a human when needed.
2. A loop that manages conversation history (messages list)
3. Validation — refuses to answer off-topic questions
4. Fallback: "This question is outside my scope — contact support"
An app that takes a financial report (PDF) and automatically extracts insights, trends and a visual chart.
2. Create an Assistant with code_interpreter + file_search
3. Ask: "Provide 5 insights and create a monthly trend chart"
4. Download the generated image via client.files.content()
A custom GPT for writing LinkedIn posts, emails and ads in a specific brand style — no code.
2. Knowledge: upload a Brand Guidelines PDF
3. Conversation Starters: "Write a LinkedIn post about..."
4. Test with 10 varied examples and tune the Instructions
An agent that takes a task in natural language and performs it by calling external APIs: Notion, Gmail, Slack.
def run_agent(user_task: str) -> str:
messages = [
{"role": "system", "content": "You are an automation agent. You have tools."},
{"role": "user", "content": user_task}
]
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=AVAILABLE_TOOLS,
tool_choice="auto"
)
msg = response.choices[0].message
messages.append(msg) # save the agent's response
if msg.tool_calls:
# run every tool the agent requested
for tc in msg.tool_calls:
args = json.loads(tc.function.arguments)
result = execute_tool(tc.function.name, args)
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result)
})
else:
# the model is done — no tool_calls
return msg.content
A Q&A system over private documents — ChatGPT answers only from your organizational knowledge, and does not make things up.
# Step 1: Indexing — Embedding the documents
def index_documents(chunks: list[str]) -> list:
response = client.embeddings.create(
model="text-embedding-3-small",
input=chunks
)
# store in Pinecone / Chroma / pgvector
return [e.embedding for e in response.data]
# Step 2: RAG Query
def rag_query(question: str) -> str:
# Embed the question
q_vec = client.embeddings.create(
model="text-embedding-3-small",
input=question
).data[0].embedding
# search for the relevant chunks (top-5)
results = vector_db.query(vector=q_vec, top_k=5)
context = "\n\n".join([r["metadata"]["text"] for r in results])
# GPT answers only from the context
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": f"Answer only based on the following information. "
f"If the answer is not in the information — say 'I don't know'.\n\n{context}"
},
{"role": "user", "content": question}
]
)
return response.choices[0].message.content
Cheat sheet — ChatGPT Cheat Sheet
Everything you need at hand — tables, templates, endpoints and common errors.
Quick model comparison
| Model | Speed | Reasoning | Hebrew | Vision | Cost |
|---|---|---|---|---|---|
| GPT-4o | Fast | Good | Great | ✓ | $$ |
| GPT-4o mini | Very fast | Basic | Good | ✓ | $ |
| o3 | Slow | Great | Great | ✓ | $$$$ |
| o4-mini | Medium | Great | Good | ✓ | $$ |
Ready-to-use Prompt Templates
Summarize in 5 key points. Each point: 1–2 sentences. Emphasize conclusions and required actions. Text: [...]
Review the code. Find: 1) bugs 2) performance issues 3) security 4) readability. Cite specific lines. Code: [...]
Generate 10 ideas for [topic]. Constraints: [X, Y]. Audience: [description]. Rate each idea 1–5 for feasibility and novelty.
Solve step by step. Show detailed reasoning. At the end: summarize the final answer clearly. Problem: [...]
Translate into business English. Keep the original tone. Explain 3 alternative translation choices for difficult terms. Text: [...]
Act as an adversary. Find 5 weaknesses in [product/process]. For each: severity, exploit vector, a fix recommendation.
Main API Endpoints
| Endpoint | Use | Python SDK Method |
|---|---|---|
| /chat/completions | Conversations, GPT-4o, Function Calling | client.chat.completions.create() |
| /embeddings | Vectors for semantic search and RAG | client.embeddings.create() |
| /images/generations | DALL-E 3 — image generation | client.images.generate() |
| /audio/transcriptions | Whisper STT — audio transcription | client.audio.transcriptions.create() |
| /audio/speech | TTS — text to speech | client.audio.speech.create() |
| /beta/assistants | Assistants API + Threads | client.beta.assistants.create() |
| /batches | Batch API — 50% discount, async | client.batches.create() |
Common errors and solutions
tenacity. For high load — upgrade to Tier 2+ in the OpenAI dashboard.tiktoken to count tokens before sending.response_format={"type":"json_object"} and "Return ONLY valid JSON" at the end of the prompt.OPENAI_API_KEY is set. Check billing in the platform.openai.com dashboard.timeout=30 to the API call and use Streaming instead of waiting for a full response.The next step
Now that you have the basics — it's time to apply them. Create an account at platform.openai.com, get an API Key, and start with the code examples from this guide.