Sunday , November 29 2026
OpenAI API in Python: JSON output, embeddings, function calling, streaming and cost control.

OpenAI API Tutorial: JSON, Embeddings, Function Calling

Updated: 28 November 2026Level: IntermediateReading time: about 11 minutesopenai Python SDK 1.x

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

ChatGPT Tutorial.

Setup

Install
pip install openai
Note: Never write your API key inside the code or share it on GitHub. Store it in an environment variable (for example setx OPENAI_API_KEY "..." on Windows or export OPENAI_API_KEY="..." on Linux/macOS). The SDK reads it automatically.
Example
from openai import OpenAI
client = OpenAI()
MODEL = "gpt-4o-mini"      # check the docs for current model names

1. JSON Output

Example
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"])
Output
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

Example
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))
Output
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

Example
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))
Output
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

Example
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_tokens to cap the answer length.
  • Use a smaller model for simple tasks.
  • Cache answers to repeated questions.
  • Handle RateLimitError with retries and back-off.
Example
print(resp.usage)    # prompt_tokens, completion_tokens, total_tokens
Note: OpenAI also offers a newer Responses API (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

  1. Ask for 5 MCQs as JSON and print them as a quiz.
  2. Embed 10 tutorial titles and find the 3 closest to a question.
  3. 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

About Machine Learning

Check Also

LlamaIndex Tutorial: Question Answering Over Your Documents

Build document Q&A with LlamaIndex: load files, index, query with sources, persist and change models.