LLM API Integration in Practice: Keys, Tools, and Per-Call Cost
This article explains how to integrate a large language model API in practice: verify endpoint, model, and billing details; create and inject API keys securely; make a first request with error handling; and use response usage data to calculate per-call cost. It also covers a key security checklist, unit conversion for pricing, and a time-aware system prompt.
1. Check Three Pieces of Information Before Integration
Before integration, open the platform console or API documentation and record the following three items. If the documentation differs from the examples in this article, follow the documentation.
| Item | What to confirm | Where to record it |
|---|---|---|
| API protocol | base_url, authentication method, and request path. base_url usually already includes the version path, for example https://example.com/v1. The actual request URL is base_url plus /chat/completions; do not append /v1 again. |
API documentation |
| Model list | Model name, context length, and whether thinking mode is supported | Model list page |
| Billing page | Unit prices and billing units for input tokens, output tokens, web search, and web reading | Billing page |
The model name must exactly match the name shown in the console. An extra space or a different case usually causes the API to return an error such as model not found.
This article does not quote any prices. Prices may change at any time, so always base cost calculations on the official page at the time you read it. When recording unit prices, also record the billing unit. Some platforms bill per million tokens, while others bill per thousand tokens. Convert to a consistent unit before doing any calculation.
2. Create a Key and Inject It Through Environment Variables
When creating a key in the console, use a name that shows its purpose, such as “blog production.” Select only the model and tool permissions that are actually needed, and do not grant extra permissions.
Do not write keys into source code, and do not commit them to a code repository. Read them from environment variables instead. On Linux or macOS, set them like this:
export LLM_API_KEY="the key you generated in the console"export LLM_BASE_URL="the base URL given in the console API documentation"export LLM_MODEL="the model name in the console model list"
On Windows PowerShell, use $env:LLM_API_KEY="...". In production, these variables are usually injected by the deployment platform or a secret management service. If you use a .env file, add it to .gitignore and use git status to confirm that it does not appear in the list of files to be committed.
Install the SDK. Python 3.9 or later is recommended:
pip install --upgrade "openai>=1.0"python -c "import openai; print(openai.__version__)"
Key Security Checklist
- Do not write keys into source code, test cases, logs, or screenshots.
- Use a separate key for each purpose so that issues are easier to locate and revoke.
- Grant only the model and tool permissions that are actually needed.
- Rotate keys every 90 days is recommended, and rotate them immediately when personnel change or a project is handed over.
- If you suspect a leak, revoke the key in the console first, then generate a new one. After that, check usage logs to confirm whether there are any unfamiliar calls.
- If the platform provides usage alerts or budget limits, set them up in advance.
3. First Call and Error Handling
The code below completes a conversation that includes time information. The current Beijing time is written into the system prompt, so the model has a clearer basis when answering questions such as “today” or “tomorrow.” The model itself has no clock, so the effect of this approach should be verified by sampling. Take a batch of questions containing time words, run them with and without the time prompt, count the proportion of correct answers, and then decide.
import osfrom datetime import datetime, timedelta, timezonefrom openai import APIConnectionError, APIStatusError, OpenAI, RateLimitErrorclient = OpenAI(api_key=os.environ["LLM_API_KEY"],base_url=os.environ["LLM_BASE_URL"],timeout=30, # Maximum wait time for a single request is 30 secondsmax_retries=2, # SDK automatically retries 429, 5xx, and connection errors twice)def build_system_prompt() -> str:now = datetime.now(timezone(timedelta(hours=8)))return f"You are a concise Chinese-language assistant. The current Beijing time is {now:%Y-%m-%d %H:%M}."def error_text(e: Exception) -> str:# In different SDK versions, the message field of the exception object may behave differently; fall back to str(e) if unavailablereturn getattr(e, "message", None) or str(e)def ask(question: str, tools=None):kwargs = {"model": os.environ["LLM_MODEL"],"messages": [{"role": "system", "content": build_system_prompt()},{"role": "user", "content": question},],}if tools:kwargs["tools"] = toolstry:return client.chat.completions.create(**kwargs)except RateLimitError as e:print(f"Rate limit triggered: reduce concurrency or request a higher quota in the console. {error_text(e)}")except APIConnectionError:print("Network connection failed: check base_url and the local network")except APIStatusError as e:print(f"API returned an error with status code {e.status_code}: {error_text(e)}")return Noneresp = ask("Is today a good day to go out? Answer briefly.")if resp:print(resp.choices[0].message.content)print(resp.usage)
resp.usage is the raw data for later cost accounting. It usually contains three fields: prompt_tokens, completion_tokens, and total_tokens. Some platforms return empty values or omit fields, so check the data before adding it directly.
