The OpenAI API gives your programs access to OpenAI’s models for text, code, images, speech and embeddings. This tutorial goes beyond the basics in the ChatGPT tutorial: structured JSON output, embeddings, function calling, streaming and cost control.
What You Will Learn
- Set up the client securely
- Get reliable JSON output
- Create embeddings for search and RAG
- Use function (tool) calling
- Stream responses and control cost
Prerequisites
Setup
pip install openai
setx OPENAI_API_KEY "..." on Windows or export OPENAI_API_KEY="..." on Linux/macOS). The SDK reads it automatically.from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4o-mini" # check the docs for current model names
1. JSON Output
import json
resp = client.chat.completions.create(
model=MODEL,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Return only JSON with keys: topic, level, summary."},
{"role": "user", "content": "Explain K-Means clustering briefly."}
]
)
data = json.loads(resp.choices[0].message.content)
print(data["topic"], "|", data["level"])
K-Means Clustering | Beginner
Explanation: response_format={"type": "json_object"} makes the model return valid JSON, which you can load straight into a Python dictionary. The prompt must mention JSON.
2. Embeddings
emb = client.embeddings.create(
model="text-embedding-3-small",
input=["What is machine learning?", "Explain ML in simple words"]
)
v1, v2 = emb.data[0].embedding, emb.data[1].embedding
print(len(v1))
1536
Explanation: Each text becomes a 1,536-number vector. Similar meanings give similar vectors – the basis of semantic search and RAG. Store them in a vector database.
3. Function Calling
import json
tools = [{"type": "function", "function": {
"name": "get_weather",
"description": "Get today's temperature for a city",
"parameters": {"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]}}}]
messages = [{"role": "user", "content": "Is it hot in Ludhiana today?"}]
resp = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)
call = resp.choices[0].message.tool_calls[0]
print(call.function.name, json.loads(call.function.arguments))
get_weather {'city': 'Ludhiana'}
Explanation: The model does not run your function – it asks you to. Your code runs get_weather("Ludhiana"), appends the result as a {"role": "tool", "tool_call_id": call.id, "content": ...} message, and calls the model again for the final answer. This is how AI agents work.
4. Streaming
stream = client.chat.completions.create(model=MODEL, stream=True,
messages=[{"role": "user", "content": "Write 5 tips to learn Python."}])
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
5. Cost and Limits
- You pay per input and output token – shorter prompts cost less.
- Set
max_tokensto cap the answer length. - Use a smaller model for simple tasks.
- Cache answers to repeated questions.
- Handle
RateLimitErrorwith retries and back-off.
print(resp.usage) # prompt_tokens, completion_tokens, total_tokens
client.responses.create) that combines chat, tools and built-in tools. The Chat Completions API shown here remains widely used; check the docs for which to prefer.Common Errors
| Problem | Cause and fix |
|---|---|
json.JSONDecodeError |
Use response_format and say “JSON” in the prompt. |
tool_calls is None |
The model chose to answer directly; check message.content. |
RateLimitError |
Slow down, add retries, or raise your account limits. |
Series
LLM series: LLM Fundamentals · Transformer Architecture · OpenAI API · Hugging Face · LangChain · LlamaIndex · Vector Databases · LLM Evaluation
Interview Questions
Q: What are embeddings used for?
Semantic search, clustering, recommendations and retrieval in RAG.
Q: How do you keep costs low?
Smaller models, shorter prompts, max_tokens, caching and batching.
Practice Exercises
- Ask for 5 MCQs as JSON and print them as a quiz.
- Embed 10 tutorial titles and find the 3 closest to a question.
- Complete the function-calling loop with a fake
get_weather.
Summary
Beyond chat, the OpenAI API offers JSON output, embeddings, function calling and streaming. Watch token usage to control cost.
Next: Hugging Face · Vector Databases
Machine Learning Tutorials, Courses and Certifications