Guide · Beginner · 11 min
Getting started with an LLM API: keys, your first request, settings, costs, and best practices
Learn how to call an LLM API, protect your key, send your first request, adjust settings, estimate costs, and handle common errors before using it regularly.

To use an LLM API, create an access key, choose a model, and send a request containing your instructions and text. The service returns a response that your program needs to check, along with usage you need to monitor. This guide walks through a reproducible first request, then covers the settings, budget controls, and safeguards you need before using the API regularly.
Understand what you are connecting
An API lets one program request a service from another. With a language model, your application generally sends messages and receives text or structured data. This lets it summarize a document, classify a request, or prepare a draft without going through a chat interface.
Making an API call does not automatically give the model access to your files, the internet, or your email. Those capabilities require additional connections and permissions. Start with a narrow task: turning a short piece of public text into a summary.
The walkthrough below uses OpenRouter, a platform that routes requests to model providers. It is a technical example, not a commercial recommendation. Its official quickstart guide, accessed October 24, 2026, documents the endpoint and method used here.
| Criterion | Direct provider API | Intermediary platform |
|---|---|---|
| Account and key | Managed with the provider | Managed with the platform |
| Model selection | The provider’s catalog | The intermediary’s available catalog |
| Data path | Application, then provider | Application, intermediary, then provider |
| Troubleshooting | Provider documentation | Platform and provider documentation |
| Budget | Terms of the direct offering | Terms of the platform and services used |
In either case, first check that the model is available and review the terms that apply to your account.
1. Prepare your account and a simple environment
Prerequisites: an account with access to your chosen API, a Bash terminal, the curl command available, and sample text containing no confidential information. The following commands are written for Bash; do not copy them unchanged into another shell.
You do not need a library for this exercise. If your computer lacks the required tools, use an environment approved by your organization and follow its installation procedure.
In the platform dashboard:
- Check the billing terms and available credits.
- Create a key dedicated to this exercise.
- Set a spending limit appropriate for your test.
- Find the usage information and the option to revoke the key.
The authentication documentation, accessed October 24, 2026, explains API keys and their credit limits. For your first connection, avoid sharing a key across several projects: doing so makes incidents and spending harder to trace.
Next, choose a model your account can access. Use the model profiles to help narrow your choice, then copy the model’s exact API identifier from the platform. The product name shown in an interface is not always enough to build a valid request.
The model benchmarks provide points of comparison. They do not replace testing with your own text, language, and expected output format.
2. Load the key without putting it in your program
An API key is an access secret. Anyone who obtains it may be able to use its permissions and spend your budget. Do not put it in a public web page, an application distributed to users, or a code repository.
In Bash, enter the key without displaying it on screen:
read -r -s -p "Clé API : " OPENROUTER_API_KEY
printf '\n'
export OPENROUTER_API_KEY
This avoids typing the secret directly into a command saved in your terminal history. It does not turn your computer into a secure vault: a process allowed to inspect your environment could still access it.
Next, enter the identifier of your chosen model:
read -r -p "Identifiant API exact du modèle : " LLM_MODEL
export LLM_MODEL
Copy only the identifier supplied by the platform. The following example assumes it contains no quotation marks or line breaks, so it can be inserted into the JSON document.
Do not ask the model to check your key by sending it in a message. Authentication belongs in a request header; the text to process belongs in the request body.
For a deployed application, use your hosting platform’s secrets management system. Keep development and production keys separate, restrict who can view them, and plan how to replace them. An environment variable is suitable for this exercise, but its protection still depends on the environment where it is stored.
3. Send your first request
The command below adapts the platform’s documented format to a summarization task. The output cap and timeouts are settings for this exercise, not published service limits.
curl --silent --show-error \
--connect-timeout 10 \
--max-time 60 \
--dump-header reponse.headers \
--output reponse.json \
--write-out 'Statut HTTP : %{http_code}\n' \
https://openrouter.ai/api/v1/chat/completions \
-H "Authorization: Bearer $OPENROUTER_API_KEY" \
-H "Content-Type: application/json" \
--data-binary @- <<EOF
{
"model": "$LLM_MODEL",
"messages": [
{
"role": "system",
"content": "Vous résumez fidèlement le texte fourni en français. N'ajoutez aucune information."
},
{
"role": "user",
"content": "Résumez en une phrase : La bibliothèque municipale ferme lundi pour réaliser un inventaire. Elle rouvrira mardi aux horaires habituels."
}
],
"max_tokens": 200,
"stream": false
}
EOF
Authorization carries the access credential. Content-Type identifies the body as JSON. model specifies the requested model, while messages contains the instructions and text.
The command saves the headers and body in separate files. It also displays the HTTP status, which helps distinguish a response from the service from a connection problem.
Read the result:
cat reponse.json
Do not simply replace the sample text with a long variable containing an arbitrary document. Quotation marks or line breaks could make the JSON invalid. To process variable input, use a JSON encoder in your programming language to build the request body.
At the end of the exercise, remove the key from the terminal environment:
unset OPENROUTER_API_KEY
This command does not revoke the key on the platform.
4. Read the response before using it
The file you receive contains a technical response envelope. In the Chat Completions format used here, the generated text is generally found in choices[0].message.content. Other fields help identify the response, explain why generation stopped, and track usage.
Check three things separately:
- The technical outcome: was the request accepted, or does the response contain an error?
- How generation ended: did the model finish normally, or did it reach a limit?
- The content: does the summary follow the source text and instructions?
A success status does not guarantee an accurate summary. In this exercise, the result must preserve the Monday closure and Tuesday reopening without inventing any additional reason.
Usage counters measure tokens, units of text that do not consistently correspond to words. Avoid using fixed conversions between words, characters, and tokens when calculating a bill.
The context window determines how much the model can process in a single call, according to that model’s rules. Input text, instructions, conversation history, and generation all use capacity that you need to check for your chosen model.
If your application needs to save a result, it must also be able to reject an empty, truncated, or inconsistent response. Simply displaying everything that comes back is a poor fit for automated processing.
5. Adjust parameters gradually
Start with a small number of parameters. Add a setting to address a problem you have observed, then compare the results using the same examples.
The parameter reference, accessed October 24, 2026, explains that support depends on the model and provider. When you omit a parameter, the provider may apply its default value.
| Parameter | Purpose | Precaution |
|---|---|---|
model | Select the model | Check the identifier and your access |
messages | Supply instructions and content | Keep roles clearly separated |
max_tokens | Cap generation | Allow enough room for the response to finish |
temperature | Adjust response variety | Do not treat it as a truthfulness setting |
top_p | Influence token selection | Avoid changing every setting at once |
stream | Receive output as it is generated | Plan for interrupted streams |
A low temperature can reduce variation in wording. It guarantees neither factual accuracy nor perfectly repeatable results across runs. For an extraction task, validating the result matters more than choosing a supposedly ideal value.
An output cap that is too low can cut off the answer. With some reasoning models, part of the budget may also be consumed without appearing in the final text. If the output is empty, inspect usage and the reason generation stopped before trying again.
For model selection itself, the guide to choosing a language model complements this approach. Keep the input text and evaluation criteria unchanged when comparing candidates.
6. Calculate the cost per successful task
For a simple text request, the basic calculation adds input and output tokens, each multiplied by its respective rate. Depending on the service, other charges may apply for caching, reasoning, tools, or specific processing options.
The following is an illustrative calculation, unrelated to any commercial rate. Assume input costs $1 per million tokens and output costs $4 per million. With 2,000 input tokens and 500 output tokens:
Entrée : 2 000 / 1 000 000 × 1 $ = 0,002 $
Sortie : 500 / 1 000 000 × 4 $ = 0,002 $
Total simulé : 0,004 $ par appel
Under those assumptions, 1,000 identical calls would cost $4, excluding other charges. These figures explain the calculation; they are neither a quote nor an estimate of your actual usage.
The useful metric is the cost per successful task. A model with a lower price per token may require more attempts, corrections, or checks. A long conversation can also send the same passages repeatedly.
For your actual budget, record the rate that applies to the selected model and provider, along with the date. Then measure representative tasks and compare the usage counters with the billing dashboard.
The LLM price calculator helps compare usage volumes. The guide to understanding LLM API pricing explains which charges to examine, while how much an AI agent really costs per month covers the expenses of an application that makes a sequence of calls.
7. Separate instructions, documents, and the expected format
A useful instruction defines the task, the authorized source, and the expected result. When summarizing a document, specify that information must come from that document and that missing details must remain missing.
Keep application rules separate from the content being analyzed. A document supplied by a user may itself contain sentences that look like commands. Your program must treat it as data, without giving it the authority to change permissions or decide where results are sent.
If the output will feed another piece of software, simply asking for JSON in the message is not enough. The documented structured output feature, accessed October 24, 2026, lets you define a schema when using compatible models.
Your application still needs to check that fields are present, their types are correct, and their values are allowed. A response that matches the schema can still contain an incorrect date or an amount that never appeared in the source document. Structural validity and accuracy for the task require separate checks.
Define an explicit outcome for missing information: an allowed missing value, a status indicating that review is needed, or a handoff to a person. Forcing the model to fill every field encourages unsupported additions.
Finally, an API does not become an agent simply because it generates structured text. Creating your first AI agent covers the next step: adding tools, state, and a controlled execution loop.
8. Protect data and control spending
Before sending a real document, identify the route it will take. When you use an intermediary, the data passes through the platform and then the selected provider. Also check the logs your own application creates.
The OpenRouter privacy policy, accessed October 24, 2026, distinguishes the platform’s practices from those of model providers. An assurance about training does not, by itself, answer questions about retention, access, or data location.
Start with public or fictional data. Remove information the task does not need, such as contact details, account identifiers, technical secrets, or attachments unrelated to the request.
For spending control, combine several safeguards: a key limit, a maximum input length, a generation cap, and a maximum number of attempts. If users can access the application, add a per-user quota so that one person cannot consume the entire budget.
Keep the key on your server. The user’s browser calls your application, which checks their permissions before querying the model. Also limit request size and the number of simultaneous calls.
Prefer logging metadata: the requested model, duration, usage, status, and request identifier. Recording complete documents and responses should serve a specific need, with defined access controls and a retention period.
9. Common problems
The platform’s documented errors, accessed October 24, 2026, help distinguish a request problem from a temporary service incident.
| Symptom | Possible cause to investigate | First action |
|---|---|---|
Status 400 | Invalid JSON or an incompatible parameter | Read the message and simplify the request |
Status 401 | Missing, invalid, or revoked key | Check that the secret was loaded |
Status 402 | Insufficient credits or budget | Check the balance and limits |
Status 403 | Permission restriction or blocking rule | Review the applicable restrictions |
Status 429 | Rate limit reached | Wait before trying again |
Status 502 or 503 | Availability incident | Retry with a bounded wait |
| Truncated or empty text | Exhausted budget or interrupted generation | Inspect the finish reason and usage |
Do not repeatedly retry an invalid request or a rejected key. For temporary incidents, increase the delay between attempts, respect the Retry-After header when present, and set an overall limit.
A client-side timeout does not prove that the provider processed nothing. Retrying may therefore incur additional usage. If your program subsequently triggers a business action, protect that action against duplicates as well.
When asking for help, keep the time, request identifier, and a minimal anonymized example. Never publish the key or the confidential document involved.
10. Check readiness for regular use
Before integrating the call into a real workflow, prepare a small set of representative cases: straightforward text, an incomplete document, a long input, an ambiguous instruction, and irrelevant content. Include situations where the correct response is to report that information is missing.
Define your criteria before comparing results. For a summary, check that facts are preserved, nothing is added, the language is correct, and the length is acceptable. For extraction, check that values match the source, fields are validated, and errors are detected.
Record the model identifier and parameters used. A change to the model, provider, or instructions warrants another check against the same cases. Measure duration and cost as well: a correct answer that arrives too slowly may not meet your application’s needs.
Finish with this checklist:
- The key is dedicated, protected, and revocable.
- The model and supported parameters have been checked.
- The first request uses data with no particular confidentiality requirements.
- The program checks errors, empty outputs, and truncated responses.
- Results are evaluated using representative examples.
- Observed costs are compared with billing.
- Attempts, usage volumes, and spending have limits.
- The scope of transmitted data and logs is defined.
You now have a foundation you can monitor: a request you understand, a checked result, and a measurable budget. Add further capabilities gradually, keeping these controls in place at every step.
Related pages
Frequently asked questions
Do I need a chatbot subscription to use an LLM API?
Access to a chat interface and access to an API are separate offerings. Check the terms of your chosen platform: a chatbot subscription does not necessarily include API credits.
Can I call an LLM API without installing a library?
Yes. An HTTP request is enough if your environment can send one. A library can make responses easier to read and errors easier to handle, but it also adds a dependency you need to maintain.
Why can a short response cost more than expected?
Billing may include a long input, conversation history sent again with each exchange, or reasoning tokens. Check the usage data rather than judging the cost by the length of the displayed answer.
Can I switch providers without changing my application?
A compatible interface can reduce the changes required, but it does not guarantee identical behavior. You still need to check supported parameters, response formats, retention policies, and results.
What should I do if an API key appears in a public repository?
Revoke it immediately, then create a new secret and update the affected applications. Removing the line from the repository is not enough: someone may have copied the key, or it may remain accessible in the repository history.