AI Services and Tools (2): APIs and Model Selection#

This chapter has two parts. The first uses the OpenAI An agreed-upon window through which programs exchange functions with each other. Think of a restaurant: the customer (your program) does not walk into the kitchen (the AI model) but orders from a set menu in a set way and gets the result back. AI companies open their models through APIs, and developers pay for the amount they request.
What It Means to Use AI Through an API#
Model providers such as OpenAI run user-facing services like ChatGPT themselves, but they also expand the AI service ecosystem by offering APIs to outside developers. Because an API lets you deliver a high-quality AI service quickly instead of building your own model, it is a very sensible choice for a startup.
And (on a somewhat different note) when non-developers ask me where to start learning programming, I used to recommend small goals such as building a dynamic page with HTML and JavaScript or scraping a web page with Python. After I integrated an AI API, my ranking changed. Wiring up an AI API is the thing I now recommend most, because it is easy, fun, and motivating. The sample code below is short and intuitive, and that is exactly why.
What You Can Do with the OpenAI API#
Text generation#
The most basic API takes text input and generates a text response. In the OpenAI Python A bundle of tools and code that makes a particular service or platform easy to use. Calling an API directly means matching request formats and authentication by hand, while an SDK lets you do the same thing with a single function such as client.responses.create(). OpenAI, Anthropic, and Google all provide SDKs for major languages such as Python and JavaScript.Responses API(client.responses.create) is the main entry point. The older Chat Completions API is still available, but the Responses API is recommended for new development. instructions corresponds to “setting the scene (system instructions),” and input holds the user input (or the conversation history). The gpt-6-luna in the examples is the lightest and cheapest tier of OpenAI’s GPT-6 generation; above it sit Terra, Sol, and Astra.
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6-luna",
instructions="You are a helpful assistant.",
input=[
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content": "Where was it played?"},
],
)
print(response.output_text)The thing to notice here is role. A role of user means “something the user said,” and assistant means “an answer the model gave earlier (conversation history).” What people usually call system instructions are the shared rules you give the AI before the conversation starts (role / tone / prohibitions / output format), and in this example they are managed separately in instructions. The five layers of context we saw in Key AI Concepts, Chapter 3 split in code like this, into instructions (fixed guidance) and input (conversation history plus the current request).
Function calling#
Seen at the API level, the Function Calling described in Key AI Concepts, Chapter 2 works as follows. Assume a [user ( The client is the program on the user’s side (a web browser, a mobile app, and so on), and the server is the company-side computer that receives and processes its requests. The server is often called the backend. Users can inspect whatever is in the client, so information that must be protected, such as the secret key (API key) for using an AI API, always stays on the server.
- When the server receives the user’s query and passes it to the model, it also sends the names, descriptions, and
Both refer to input values passed to a function. A parameter is the slot that defines what input a function takes, such as “takes a city name,” and an argument is the value actually placed in that slot when calling it (for example, “Seoul”). In Function Calling, the model reads the parameter specifications and returns suitable arguments.
specifications of its functions. There can be several functions, and all of them are implemented on the server. - When the model generates its response, if the situation calls for a function call, it includes “which function to call with which arguments” in the response and sends that to the server.
- The server calls that function. The function contains whatever algorithms and external API calls it needs.
- The server sends the function’s result back to the model, and only then does the model generate the final response, which the server receives and passes on to the user.
from openai import OpenAI
import json
client = OpenAI()
tools = [{
"type": "function",
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}]
response = client.responses.create(
model="gpt-6-luna",
input=[{"role": "user", "content": "What's the weather in Seoul?"}],
tools=tools,
)
# Check whether the model requested a function call, then have the server run the real function.
for item in response.output:
if item.type == "function_call" and item.name == "get_weather":
args = json.loads(item.arguments)
result = {"city": args["city"], "temp_c": 27, "sky": "clear"} # in practice, call a weather API
final = client.responses.create(
model="gpt-6-luna",
previous_response_id=response.id,
input=[{"type": "function_call_output", "call_id": item.call_id, "output": json.dumps(result)}],
)
print(final.output_text)Adding Actions to a custom GPT so it can call external APIs is, from the server’s point of view, the same concept: “defining the tools (functions) the model may call when it needs them.”
Image generation#
There is an API that generates images from text (a prompt). Image generation uses a dedicated image model (the GPT Image family) separate from the text generation models. GPT Image models return the generated image as a A way of writing non-text data such as images or audio using only letters, digits, and a few symbols. It is used to carry a file through a channel that can only pass text (for example, an API response). The receiving side has to decode the string back into the original data before saving it as an image file, and the string is about a third larger than the original file.
import base64
from openai import OpenAI
client = OpenAI()
response = client.images.generate(
model="gpt-image-2.6-flare",
prompt="a white siamese cat",
size="1024x1024",
quality="medium", # low / medium / high, etc.
n=1,
)
image_bytes = base64.b64decode(response.data[0].b64_json)
with open("siamese_cat.png", "wb") as f:
f.write(image_bytes)Running the code above saves the generated image as a PNG file. Prompt engineering matters if you want specific details. Besides generating from a text prompt, you can also supply an existing image and a An area that marks only the part of an image to change. You mark it by making a separate image of the same size and format as the original, with the part to change left transparent, and the model redraws mainly that part. It is useful when you want to change only the background of a photo or remove a specific object.client.images.edit()). With the Responses API’s image_generation tool, you can also have the model create images in the middle of a conversation. The chapter illustrations in this book were made the same way (with a different provider’s image model), by supplying one style-reference image and directing a different scene for each chapter.
Vision#
You can supply image data together with a request about it (a text prompt) and generate a text response. You can ask for a description of the image, ask whether a particular object appears in it, compare several images with one another, and so on.
from openai import OpenAI
client = OpenAI()
img_url = "https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg"
response = client.responses.create(
model="gpt-6-luna",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": "What's in this image?"},
{"type": "input_image", "image_url": img_url},
],
}
],
)
print(response.output_text)[Example response]
This appears to be Vincent van Gogh's painting "La Mousmé" (1888). A young woman sits in a curved bentwood chair against a pale mint-green background. She wears a red-and-blue striped jacket with orange buttons and a blue skirt with orange polka dots, and holds a small sprig of pink and white flowers. The bold brushstrokes and vivid, contrasting colors are typical of his Post-Impressionist style.Text to speech#
There is also a feature that turns text into speech. Until now, the default was the Speech API (client.audio.speech) with a dedicated TTS model (gpt-4o-mini-tts, plus the previous-generation tts-1 and tts-1-hd): you pick a preset voice and a file format (MP3, WAV, and so on), and direct the tone or emotion with instructions.
These dedicated TTS models, however, are scheduled to shut down on January 6, 2027, and the successor OpenAI recommends (gpt-realtime-2.1-mini) runs on the Realtime API, not the Speech API. Instead of returning one audio file per request, the Realtime API keeps a connection open and streams speech back and forth in real time. The center of gravity for voice is shifting from “an API that takes text and returns an audio file” to “a session where you talk back and forth in real time.” If you are building a new app that talks with users by voice, OpenAI suggests starting with GPT-Live, its conversational voice model. Because the code differs a lot depending on how you connect (browser, server, or phone), this chapter points you to the official audio guide instead of showing code.
Speech to text#
There is an API that takes audio data and produces the corresponding text, with support for many languages. This feature uses a dedicated Writing down recorded speech as text. In AI, it mostly refers to speech recognition work that produces meeting notes, subtitles, or call records. Unlike translation, it keeps the words in the language they were spoken.gpt-transcribe). The previous-generation whisper-1, gpt-4o-transcribe, and gpt-4o-mini-transcribe are scheduled to shut down on February 26, 2027.
from openai import OpenAI
client = OpenAI()
with open("meeting.mp3", "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model="gpt-transcribe",
file=audio_file,
prompt="A meeting about AI models. Model names such as Llama and GPT come up.",
)
print(transcription.text)As in the example above, passing a text prompt along with the audio improves transcription quality. For example, when the model hears “llama,” it is not obvious whether to write the animal or Meta’s AI model “Llama,” but telling it what the recording is about reduces such mistakes. gpt-transcribe also accepts a keywords hint, a list of terms you expect to appear in the recording. On the other hand, timing information for each word (timestamps) is officially supported only on whisper-1, which is scheduled to shut down. If you are building something that truly needs timing, such as subtitles, check the alternatives before the shutdown.
Embeddings#
The embeddings described in Key AI Concepts, Chapter 1 are also offered as a dedicated API. You put in text and get out a numeric vector; you store those vectors, then compute the distance to a query vector to find “documents that are close in meaning.” The indexing and retrieval stages of RAG are built on top of this API.
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
model="text-embedding-3-small",
input="Refunds can be requested within 7 days of purchase.",
)
vector = response.data[0].embedding # a list of 1536 floatsModeration#
There is a free API that takes text or images and checks them for harmful content. It scores the text across categories, such as whether it contains sexual content or hateful content. You use it as a safeguard before feeding user input to a model, or before showing model output to a user.
from openai import OpenAI
client = OpenAI()
response = client.moderations.create(input="Hello world!!")
print(response.results[0].flagged) # True / FalseConversation state and built-in tools#
So far we have looked at APIs that handle one-off requests. To build a ChatGPT-like chatbot inside your own app, you also need “remembering the previous conversation” and “built-in tools such as file search or code execution.” In the past a separate Assistants API was offered for this, but that API was shut down in August 2026. Today the Responses API alone does the same job.
- Conversation state: chain onto the previous response with
previous_response_id, or create a conversation on the server with the Conversations API and continue it through theconversationparameter. The client no longer has to resend the conversation history on every turn. - Built-in tools: specify OpenAI-hosted tools such as
file_search(search over uploaded files),code_interpreter(run Python),web_search, orimage_generationintools, and the model calls them on its own when needed. Unlike the Function calling described above, OpenAI’s servers execute the tools for you.
from openai import OpenAI
client = OpenAI()
# Create a Conversation that stores the dialogue state on the server.
conversation = client.conversations.create()
while True:
user_input = input("\nuser > ")
if user_input.lower() in ["exit", "quit"]:
break
response = client.responses.create(
model="gpt-6-luna",
instructions="You are a personal math tutor. Write and run code to answer math questions.",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
conversation=conversation.id,
input=user_input,
)
print("assistant >", response.output_text)Parameter names and tool types can change, so check the official documentation when you actually implement this.
Other Model Providers’ APIs Share the Same Structure#
APIs from other model providers such as Anthropic (Claude) and Google (Gemini) share the same broad outline of “text generation / vision / tool calling / embeddings / built-in tools.” Only the parameter names and response formats differ. For example, the same text generation written with the Anthropic SDK looks like this.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5-5",
max_tokens=1024,
system="You are a helpful assistant.",
messages=[{"role": "user", "content": "Where was the 2020 World Series played?"}],
)
print(message.content[0].text)A feature in which the model provider briefly stores the opening part that is identical across many requests (system instructions, a long reference document, and so on) and reuses it. Re-reading the stored part is billed at a much lower rate than regular input, and responses get faster too. That is why the basic cost-saving rule is to put unchanging content at the front of the prompt and content that changes every time at the end. Whether it applies automatically or must be marked explicitly differs by provider. Middle code that connects different formats. Like a travel power adapter, your service always requests “generate an answer” the same way, and the adapter converts that request into the format of OpenAI, Anthropic, or Google. When you switch providers you only fix the adapter, and the rest of the code stays untouched.instructions has become system and input has become messages, but the structure is identical. Once you learn one provider’s API, the cost of moving to another is small. Details such as how
Criteria for Choosing a Model#
Once you know what an API can do, the next question is “which provider’s model should I use?” The decision criteria a solo startup actually runs into are summarized below.
| Criterion | What to check | Why it matters |
|---|---|---|
| Tier | Top-tier / balanced / lightweight models within the same generation | Different tasks need different levels of intelligence. Classification and summarization are fine on a lightweight model; only complex reasoning needs the top tier |
| Cost structure | Input / output prices, cache-read price, A way of handing over non-urgent requests all at once and receiving the results later. Instead of an immediate answer, requests are usually processed within 24 hours, and in return the price is discounted by about half. It suits work users do not wait on, such as classifying or summarizing thousands of documents. discounts | Agent workloads have far more input than output, so the cache price drives the real cost |
| Context length | Maximum token count and actual quality on long documents | Bigger is not automatically better; what counts is whether the model keeps the key points in a long input |
| Tool calling · structured output | Function Calling reliability, Structured output is a feature that makes the model answer with data fitted to a fixed template instead of free-form sentences. The blueprint for that template is the JSON schema, which defines fields and formats such as “name is text, price is a number, category is one of three.” When an answer follows the schema, a program can store it or show it on screen right away without extra cleanup. compliance | To put a model in a product, “keeping to the format” matters more than “speaking well” |
| Latency and throughput | Time to first token is how long it takes from sending a request until the first character of the answer appears, and it drives how responsive the service feels to users. Tokens per minute is the maximum number of tokens you can submit in one minute; go over it and requests are rejected. The limit rises with your account’s usage history and pricing tier. | Conversational UIs are bottlenecked by latency, batch jobs by throughput |
| Data policy · A geographic unit in which a cloud company operates a cluster of data centers. Regions are divided into places such as Seoul, Tokyo, and US East, and the region you choose determines which country your data is physically stored and processed in. If you handle data with restrictions on cross-border transfer, such as personal or financial data, the choice of region can become a contract condition. | Whether inputs are used for training, which region the data stays in | If you serve B2B customers or regulated industries, this criterion overrides the rest |
| Ecosystem | SDK quality, coding agents, MCP support | A good fit with the tools you already use lowers operating cost |
There are three principles I apply in practice.
First, split the work and mix tiers. Even within a single product, classifying user queries, summarizing documents, and generating the final answer require different levels of intelligence. Use the top-tier model for every call and your costs multiply; use a lightweight model for every call and quality collapses. Decide “the minimum tier this task needs” at each call site, and use Measuring the quality of a model’s output against a fixed set of test questions. You collect dozens to hundreds of inputs likely to appear in the real service along with the answers you expect, and each time you change the model or prompt you run the same questions and compare scores. It lets you check, without relying on gut feel, whether “quality holds up even if we switch to a cheaper model.”
Second, block A state in which you are so tied to one company’s products or formats that moving to another company becomes difficult. If moving is expensive, you have to keep using the product even when prices rise or quality drops. Because models and prices in AI change every few months, it pays to build a structure you can move from the start.
Third, let security requirements decide the deployment form. Choosing where to run the model means picking a point on the spectrum below.
One misconception about A service in which a cloud company runs and manages AI models for you. Amazon Bedrock, Google Cloud’s Gemini Enterprise Agent Platform (formerly Vertex AI), and Microsoft Foundry are typical examples, and you can use models from several companies just by calling an API, without preparing servers yourself. Because the models run inside that cloud, a company already using it can easily keep data management and security policies in one place.
Subscriptions and APIs Are Different Products#
Finally, one trap developers often fall into. Because a monthly subscription to a coding agent is far cheaper than consuming the same volume through the API, it is tempting to think “what if I hook my subscription account up to my service’s backend and use it cheaply?” The answer is “you can’t.” A subscription is an individual’s right to use a product the service provider controls; having your product call a model on behalf of its users must be built on the separate economy called the API. The terms of service say so, and attempts to spend subscription quotas through third-party routes have been blocked.
That said, 2026 brought a few official bridges between subscriptions and the API. One is API credits bundled with higher-tier subscriptions. ChatGPT Pro and Business subscribers, and Claude Max, Ultra, and Team subscribers, receive a fixed amount of API credit each month to build their own apps and agents (unused credit does not roll over to the next month). This is not spending subscription quotas through the API; it is a subscription benefit that adds a slice of the API product on top. The other is OpenAI’s Sign in with ChatGPT. When a user signs in with their ChatGPT account, an approved app can process that user’s AI requests on their ChatGPT plan. It uses the user’s subscription, not yours, and for now it is open only to open-source clients and selected approved partners. Anthropic still does not allow unapproved third-party products to offer Claude subscription login.
So a solo startup’s AI costs fall into two buckets: the subscriptions I use to do my own work (coding agents, chat services) and the API calls my product makes on behalf of its users. Keeping the two separate rather than mixing them is the starting point of cost design. API credits that come with a subscription are best seen as a benefit that offsets part of the API side. The other concrete ways to reduce the API side (caching, batching, tier routing) are covered in “Adding AI Features to a Product” in the implementation chapters.
Summary#
- An LLM API consists of text generation, tool calling, images, vision, audio, embeddings, moderation, and built-in tools, and the structure is the same across providers.
- Choose a model on seven criteria: tier, cost structure, context, tool-calling reliability, latency, data policy, and ecosystem.
- Mix tiers per task, block vendor lock-in with one adapter layer, and match the deployment form to security requirements.
- The subscriptions I use and the API my product calls are different products, and their costs are managed separately. API credits bundled with higher-tier subscriptions are a benefit that offsets API costs.