What Is Chat Completions? How to Write the messages Array (2026)
Chat Completions is a type of HTTP API: you send the model an ordered list of messages, and it returns the next reply. The most common path is /v1/chat/completions. The format was popularized by OpenAI's API, and many providers and gateways have since offered compatible endpoints with the same name. So "what is chat completions" can be understood simply: a POST request with messages in the body, and a response with choices.
This article covers how to write the request, how to read the response, and how to continue a multi-turn conversation, then ends with a checklist for when things go wrong. For field-level details, defer to each provider's official documentation; compatibility is not identical across providers.
What does a minimal request look like?
curl https://your-endpoint/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "model name, see your provider docs",
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain HTTP status code 404 in one sentence."}
]
}'
Usually only two fields are required: model and messages. Others such as temperature, max_tokens (the field name may differ across endpoints and models), and stream are optional. Whether they are supported, and whether the names match, depends on your provider's documentation.
The endpoint and key correspond to the base URL and the API key. If those are unfamiliar, start with what a base URL is and what an API key is.
Which roles can go in messages?
messages is an array, and each element has at least a role and content. The three basic roles:
| role | Who is speaking | Typical use |
|---|---|---|
| system | The developer | Set identity, tone, output format, and constraints |
| user | The user | Ask questions, supply material, assign tasks |
| assistant | The model | Earlier model replies, used to reconstruct the conversation history |
Beyond these, tool-calling scenarios add a tool role, and OpenAI's newer model documentation also has a developer role that works much like system. These are advanced topics; beginners can get by with the first three. Which roles are available depends on your provider's documentation.
Does message order matter?
Yes. The model reads context in array order. The usual pattern:
- Put system first, usually as a single message.
- After that, user and assistant alternate.
- The last message is generally user, which is the question you want answered this turn.
A few providers impose extra rules, for example requiring the first non-system message to be user, or disallowing two consecutive messages with the same role. When you get a 400 error, check the order against the official docs first.
In Anthropic's own Messages API, system is not part of the messages array but a separate top-level field. This is a typical difference between the two formats; see how the Anthropic and OpenAI APIs differ for details.
How do I read the response?
On success the response is JSON. The core structure looks like this (some fields omitted):
{
"id": "chatcmpl-...",
"object": "chat.completion",
"model": "...",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "404 means the server cannot find the requested resource."},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 32, "completion_tokens": 18, "total_tokens": 50}
}
The numbers above are only examples. Remember three parts when reading it:
- choices: an array of candidate replies. By default there is just one, so
choices[0].message.contentis the answer. - finish_reason: why the model stopped.
stopgenerally means a normal finish;lengthmeans the output hit the length limit and was cut off, so raise the limit or shorten the task. For other values, see the docs. - usage: how many input and output tokens this request used. Billing is based mainly on this. For what a token is, see what a token is in an LLM.
How do multi-turn conversations actually work?
The API itself is stateless: the server does not remember what was said in earlier turns. To make the model "remember", you resend the history with every request.
First request:
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "What is DNS?"}
]
After the model replies, you append its reply as an assistant message, add the new question, and send that as the second request:
"messages": [
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "What is DNS?"},
{"role": "assistant", "content": "DNS resolves domain names to IP addresses."},
{"role": "user", "content": "How does it relate to a CDN?"}
]
The model can understand "it" in the second question because the first two messages of history were sent along with it.
This has two practical consequences:
- The longer the conversation, the more input tokens each request uses, so cost and latency both rise.
- The total history cannot exceed the model's context window, so long conversations need truncation or summarization on your side. Check the model documentation for the window size.
Agent-style tools send a large amount of history and tool output on every turn, which makes them especially token-hungry; see how to estimate AI agent task costs.
Hands-on: a multi-turn loop in Python
import os, requests
url = "https://your-endpoint/v1/chat/completions"
headers = {"Authorization": f"Bearer {os.environ['API_KEY']}"}
messages = [{"role": "system", "content": "You are a concise technical assistant."}]
while True:
q = input("You: ")
if not q:
break
messages.append({"role": "user", "content": q})
r = requests.post(url, headers=headers, timeout=60,
json={"model": "model name", "messages": messages})
r.raise_for_status()
reply = r.json()["choices"][0]["message"]["content"]
messages.append({"role": "assistant", "content": reply})
print("Model:", reply)
The key is the two append calls: add the user message at the start of each turn, then add the assistant message once you have the reply. Keep the key in an environment variable; do not write it into code or commit it to a repository.
What should I check when it errors?
| Symptom | Check first |
|---|---|
| 401 | Whether the API key is correct and the header is Authorization: Bearer ... |
| 404 | Whether the endpoint has an extra or missing /v1, or a typo in the path |
| 400 | Whether the JSON is valid, and whether the model name, messages order, and roles are legal |
| 429 | You hit a rate or quota limit; retry later and check your account quota |
| 5xx or timeout | A server or network problem; check /status and /down to see whether it is an official outage |
If you are calling overseas APIs from mainland China and see slow connections or timeouts, see how to judge AI API latency from China, and use the online speed test on the cdnping homepage to see first-connection and round-trip times from your current network to each endpoint.
How can I try several models without changing much code?
Because many providers are compatible with this format, switching models often requires changing just three things: the endpoint, the API key, and the model name. AGI Plan is one such aggregating gateway: monthly subscription, payment in RMB, no overseas credit card needed, compatible with both the OpenAI and Anthropic API formats. Tools like Claude Code and Codex only need a single endpoint change, and one quota can be switched across multiple capability groups. Some models are marked "outside China only"; see agiplan.dev/models for specifics. The site states that it is not an officially authorized channel. AGI Plan is a commercial partner of cdnping; for setup steps, see agiplan.dev/startup.
Next steps
- Send your first request with the curl command above and confirm you get
choicesback. - Run the Python loop and watch how
usagegrows as the conversation gets longer. - If you are not yet sure what an "API" is, read what an API is first.
- If you need to get your own key, see how to get an OpenAI API key or how to get a Claude API key.