Sub topic 1
What an LLM API Call Is: HTTP, JSON, and Endpoints
Prerequisites
You should know basic Python or another programming language, JSON, HTTP requests, status codes, environment variables, and terminal commands. This chapter uses the common chat-completions request shape. Providers may use different URLs and field names.
HTTP, JSON, and Endpoints
An LLM API call is an HTTP request from your program to a hosted model. HTTP defines how the request travels. JSON is the structured text used for its data. An endpoint is the URL that receives a particular kind of request.
A request usually includes:
- An HTTP method, such as
POST - A URL, such as
/v1/chat/completions - Headers, including authentication and content type
- A JSON body containing the model input
Authenticating with an API Key
An API key is a secret value that identifies and authorizes your application. Send it in an Authorization header. Store it in an environment variable rather than placing it in source code or committing it to a repository.
curl https://api.openai.com/v1/chat/completions \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d @- <<EOF
{
"model": "$LLM_MODEL",
"messages": [
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what an API key is in one sentence."}
]
}
EOFBuilding a Chat Request
The model field selects the model. The messages array holds the conversation. Each message has a role and content.
systemsets behavior or application rules.usercontains the user's request.assistantrepresents an earlier model response.
The endpoint receives the complete JSON body. It does not automatically know your application's conversation history.
Reading the Response
A successful response is also JSON. The generated text is usually in choices[0].message.content. The finish_reason explains why generation stopped, such as reaching a natural end or a token limit. The usage object reports input, output, and total tokens.
Exercise
Which request component tells the server which model to use, and where should the API key be stored?
Show answer
The model field selects the model. Store the API key in an environment variable and send it through the Authorization header.