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

An engineer comparing a central core with plugs of many shapes against a price gauge

As of · November 2026. The sample code targets the Responses API in the OpenAI Python SDK; replace the model names with the latest models available when you run it. Check parameter names and the model list in the official documentation.

This chapter has two parts. The first uses the OpenAI as an example to give you a feel for what you can do with an LLM API, and the second lays out the criteria for choosing what fits your service among the many model providers and models. The first part has a lot of Python sample code, but most of it is short and simply structured. Even if you are not a developer, I recommend reading through it once, following “what goes in and what comes out” rather than trying to understand every line. It will help you understand “what I can do” with an API and set a direction.


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.

User appWeb · mobile · chatMy server (backend)API keys · prompt assembly · toolsRate limits · logs · cost trackingRAG retrieval · validation · cacheNever put API keys in the clientModel APIText · VisionImage · AudioEmbeddings · ModerationTool calls · Built-in tools(OpenAI · Anthropic · Google …)User ↔ my server ↔ model API. The model is a swappable part; the value comes from what my server does.
The basic structure of an API-based AI service. The model call is only one piece of the whole.

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 , the 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 () ↔ server ↔ model] structure.

  1. When the server receives the user’s query and passes it to the model, it also sends the names, descriptions, and specifications of its functions. There can be several functions, and all of them are implemented on the server.
  2. 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.
  3. The server calls that function. The function contains whatever algorithms and external API calls it needs.
  4. 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 string rather than a URL, so you need to decode the data and save it to a 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 to produce an edited image for that region (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 model (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 floats

Moderation#

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 / False

Conversation 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 the conversation parameter. 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, or image_generation in tools, 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)

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 works (covered later) and the format of tool-call responses do differ by provider, though, so when you actually switch providers it is safer to keep a thin that absorbs those differences.


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.

CriterionWhat to checkWhy it matters
TierTop-tier / balanced / lightweight models within the same generationDifferent tasks need different levels of intelligence. Classification and summarization are fine on a lightweight model; only complex reasoning needs the top tier
Cost structureInput / output prices, cache-read price, discountsAgent workloads have far more input than output, so the cache price drives the real cost
Context lengthMaximum token count and actual quality on long documentsBigger is not automatically better; what counts is whether the model keeps the key points in a long input
Tool calling · structured outputFunction Calling reliability, complianceTo put a model in a product, “keeping to the format” matters more than “speaking well”
Latency and throughputConversational UIs are bottlenecked by latency, batch jobs by throughput
Data policy · Whether inputs are used for training, which region the data stays inIf you serve B2B customers or regulated industries, this criterion overrides the rest
EcosystemSDK quality, coding agents, MCP supportA 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 to confirm the choice.

Second, block with a single adapter layer. Models change every few months, and so do prices. If your prompts and business logic are bound directly to one SDK’s response format, switching providers becomes expensive. Wrap the call sites thinly, and “which model is cheap and good this month” becomes a single setting.

Third, let security requirements decide the deployment form. Choosing where to run the model means picking a point on the spectrum below.

Public APIOpenAI · Anthropic · GoogleManaged platformAWS · Google · MicrosoftPrivate VPCNetwork isolationSelf-hostedvLLM · Ollama · Air-gappedEasiest to startLatest models right awayData stays inside the cloudMany providers, one APIBypasses public internetRegulated-industry needsOpen-weight models onlyHighest ops burdenMoving right raises security and control, and raises cost and operational burden along with them.
A solo startup usually starts on the left and moves right when customers bring security requirements.

One misconception about is worth clearing up: a service like Amazon Bedrock is not “a dedicated line to the model provider.” The model itself runs inside the cloud provider’s infrastructure, so the core value is that your data is never sent directly to the company that built the model, you can choose the region where it is processed (if you turn on the option to spread processing across regions, it moves only within the geographic scope you set), and your inputs and outputs are not used for training. If you serve security-sensitive B2B customers, that one sentence can decide whether a deal closes.


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.