LLM API Integration Guide: API Keys, Compatible Protocols, and Streaming
A practical walkthrough for integrating large language model (LLM) APIs. It explains how to obtain and securely store API keys, the conventions of chat-completions-style compatible endpoints, how to verify connectivity with a single request, how to implement streaming (SSE) output using only the Python standard library, and how to harden an integration for production with timeouts, retries, rate limiting, context and cost control, key governance, and observability.
When teams integrate a large model service for the first time, they usually run into two kinds of problems. The first is careless credential management: API keys get hardcoded into source files or committed to repositories, which makes auditing and rotation awkward. The second is client code that is tightly coupled to a single vendor’s proprietary protocol, so switching models or running a canary deployment becomes expensive to retrofit. This article walks through a reusable integration path in the order “prepare keys → define the interface contract → verify connectivity → add streaming → harden for production,” with examples you can run directly.
1. Know the two integration styles first
Large model services generally come in two integration styles.
- Native APIs: They fully expose a platform’s distinctive parameters, such as chain-of-thought control, structured output, and tool-calling configuration. They are expressive but tightly bound to that platform.
- Compatibility-style APIs: They follow the request/response conventions of mainstream chat-style interfaces, using paths like
POST /v1/chat/completionsand amessagesarray. Many model providers offer such endpoints (referred to as “compatible APIs” in this article) so that existing clients can switch models with only minor configuration changes.
If your project already uses a chat-style client library, or you need to run A/B tests across multiple models, go with the compatible API first, since it has the lowest migration cost. When you need to make deep use of a specific model’s proprietary parameters, extend with the native protocol. Both channels can coexist: wrap them uniformly in your business layer so that callers on top are unaffected.
The core conventions of a compatible API are as follows:
| Element | Typical value | Purpose |
|---|---|---|
| Method / path | POST /v1/chat/completions | Initiate a chat completion request |
| base_url | https:// |
Fill in per the provider’s documentation; check one by one whether the path includes a version number |
| Auth header | Authorization: Bearer |
Lets the server identify the caller and verify permissions |
| Request body | model, messages, stream, max_tokens, temperature, etc. | Specifies the model, conversation history, and generation-control parameters |
Here, model is the model identifier defined by the provider. You can only use the values listed in the official documentation; you cannot make them up. In the message body, the system message sets the role and constraints, the user message carries user input, and assistant messages can be filled back in to preserve context. Python’s standard library urllib is enough to cover everything from connectivity checks to streaming output, so no third-party dependency is required.
2. Step one: obtain the API key and store it securely
An API key is the credential for calling a large model service. It serves both as identity authentication and as the definition of which models the key can access and which quota it consumes. Both its issuance and storage should follow the principle of least privilege.
1. Create a key in the console
- Sign in to your platform’s console and open the API Key (or access credential) management page.
- Click Create and select the project or resource the key is allowed to access. If the target project does not appear in the list, import or create it first from the project management page.
- Give the key a clear, traceable name and purpose, for example
chat-demo-2025. - The key is shown in full only once at creation time, so save it immediately to a key-management tool or your team’s key vault.
2. Inject it via environment variables instead of hardcoding it
# Only effective in the current terminal session; cleared when the terminal closesprintf 'Gemini API Key: 'read -rs GEMINI_API_KEYexport GEMINI_API_KEYprintf '\n'
- The
-sflag onreaddisables echo, and-rprevents backslash escaping, so a key containing\is not misinterpreted. - Only the variable name should appear in code. Real keys must not show up in public articles, screenshots, or demo repositories; use placeholders such as
<YOUR_API_KEY>consistently in examples. - On Windows, you can set a variable of the same name through the system’s environment variable settings, or run
$env:GEMINI_API_KEY = '<YOUR_API_KEY>'in the current PowerShell session. The examples below work the same way.
3. Add safeguards around the key
- Add local config files such as
.envto the.gitignoreat the repository root. Store keys centrally in.envand load them with a library like python-dotenv, purely as a supplement to environment variables. - Scan for secrets before committing, using open-source tools such as git-secrets or gitleaks.
- Use
printf '%s' "$GEMINI_API_KEY" | wc -cto confirm the key’s length and character count are as expected, to diagnose cases where “the variable exists but is empty” or “pasted content includes extra spaces or newlines.” When an unquoted variable is expanded, whitespace gets truncated. - Use separate keys for production and testing, which makes it easy to apply rate limiting, metering, and revocation per environment. Divide permissions by project or application so that a single key is not shared across multiple systems.
3. Verify connectivity: rule out environmental factors with one request
Once configuration is done, use a single minimal request to verify that network, authentication, and the model identifier are all correct before writing business code. Here is an example using Shell:
curl -sS -o response.json -w '\nHTTP %{http_code}\n' \'https://generativelanguage.googleapis.com/v1beta/openai/chat/completions' \-H "Authorization: Bearer $GEMINI_API_KEY" \-H 'Content-Type: application/json' \-d '{"model": "gemini-4-hydrogen","messages": [{"role": "user", "content": "Reply with only one word: connected"}],"max_tokens": 64,"temperature": 0}'
Parameter notes:
-sSsilences the progress meter but keeps error messages;-owrites the response body to a file, so the status code and body are not mixed together;-wprints the HTTP status code;- The Authorization header uses a variable reference. Putting the key in the header rather than in plaintext on the command line reduces the chance of it entering shell history.
The success criterion is simple: HTTP 200, and choices[0].message.content in the response contains actual body text. Troubleshooting order:
| Situation | Common cause | Suggested action |
|---|---|---|
| Connection timeout, unable to connect | Network policy, proxy, DNS resolution | Check egress rules and proxy configuration; confirm the domain is in the access allowlist |
| 401 / 403 | Missing or malformed key, or no permission | Print the variable length to confirm it is not empty; check for a stray space before Bearer; confirm the key’s project has the model enabled |
| 404 | base_url version or path mismatch | Compare the path character by character against the official documentation |
| 400 | Nonexistent model identifier, malformed message format | Check the model identifier; confirm each entry in messages has both role and content |
| 429 | Rate limit or insufficient quota | Reduce concurrency and retry with backoff |
| 5xx | Server-side error | Retry with backoff; contact the provider if it persists |
For a short test, keep max_tokens small (such as 64) and set temperature to 0 so results are as deterministic as possible and unnecessary token consumption is reduced.
4. Python streaming output: faster first byte, more stable connections
Streaming output (stream: true) lets the server push incremental text as generation progresses. Its value comes from three things:
- Users see the first character sooner, so perceived latency drops significantly;
- The generation task is split into many small transfers, making it less likely to hit an overall response timeout;
- The answer can be interrupted midway, saving compute and cost.
Below is an implementation that relies only on the Python standard library:
"""Receive chat completion results via SSE streaming, using only the Python standard library."""import jsonimport osimport urllib.errorimport urllib.requestBASE_URL = os.environ["GEMINI_BASE_URL"] # Example: https://<domain>/v1beta/openaiAPI_KEY = os.environ["GEMINI_API_KEY"]MODEL = os.environ.get("GEMINI_MODEL", "gemini-4-hydrogen")payload = {"model": MODEL,"messages": [{"role": "system", "content": "You are a rigorous technical assistant; answer concisely and accurately."},{"role": "user", "content": "Explain what streaming output is in three paragraphs."},],"stream": True,"max_tokens": 512,"temperature": 0.2,}request = urllib.request.Request(f"{BASE_URL}/chat/completions",data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),headers={"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json","Accept": "text/event-stream",},method="POST",)def iter_text_deltas(response):"""Parse SSE data lines and yield incremental text segments."""for raw_line in response:line = raw_line.decode("utf-8").strip()if not line.startswith("data:"):continuechunk = line[5:].strip()if chunk == "[DONE]":returntry:choices = json.loads(chunk).get("choices") or []delta = (choices[0].get("delta") or {}).get("content")except (json.JSONDecodeError, IndexError):continue # Fault tolerance: a single malformed event should not break the whole streamif delta:yield deltatry:# timeout constrains both connection establishment and idle time during readswith urllib.request.urlopen(request, timeout=120) as response:if response.headers.get_content_type() != "text/event-stream":# Error responses are usually application/json; read the body first, then handle uniformlyraise RuntimeError(response.read().decode("utf-8", errors="replace"))for piece in iter_text_deltas(response):print(piece, end="", flush=True)print()except urllib.error.HTTPError as exc:print(f"Request failed with HTTP {exc.code}: {exc.read().decode('utf-8', errors='replace')}")except urllib.error.URLError as exc:print(f"Network error: {exc.reason}")
A few easily overlooked details:
- Parsing: The streaming response of a compatible API is based on SSE (Server-Sent Events). Each line starts with
data:, the JSON payload is followed by a[DONE]marker, and the stream ends there. The incremental text is atchoices[0].delta.content; the first delta usually carries arolefield, and the last segment’sfinish_reasonindicates the stopping reason (such as a normal finish or hitting the length limit). - Printing:
printmust useflush=True. Otherwise, when stdout is redirected to a file or pipe it becomes block-buffered, the content only appears all at once at the end, and the streaming effect disappears. - Keeping the connection alive:
urllibopens a new connection on every request. In high-concurrency scenarios, switch to an HTTP client with connection pooling and enable keep-alive; otherwise frequent handshakes drive up latency. - Persisting deltas: For session storage or auditing, accumulate the segments in the loop and write them to a persistent store such as object storage once at the end, avoiding frequent database writes.
- Scope of use: Raw data such as prompts and conversation records should only be used within the service scope where it is genuinely needed, and should not be stored in full in logs.
5. Engineering hardening: from “it works” to “it’s stable”
1. Timeouts, retries, and rate limiting
- Timeouts: For streaming requests, the timeout mainly constrains the idle time of a single read; for non-streaming requests, the timeout should be longer than the model’s maximum generation time.
- Retries: Retry only recoverable errors such as 429, 5xx, and connection resets, using “exponential backoff plus random jitter,” for example 1s, 2s, 4s with a random offset, capped at 2–3 attempts. Otherwise, many clients retrying at the same time can trigger an avalanche.
- Rate limiting: The client should also limit concurrency and requests per second, aligned with the platform-side quota, so that traffic bursts do not trigger 429.
2. Context and cost management
- Every request must send back the full history it needs, since the server usually keeps no session memory. Trim context using an approach such as “system prompt + last N turns + summary.”
- Set a reasonable output-length limit to control cost and avoid overly long answers.
- Parse the token-usage fields from the response and track consumption by model and by business line. When long-term retention is needed, sync it to a data warehouse or set threshold alerts through monitoring.
3. Key governance
- Never hardcode keys in code, frontend pages, or distributed client packages; always call through a server-side proxy.
- For high-value scenarios, consider using short-lived temporary credentials.
- Establish a regular rotation mechanism and revoke promptly when a person or application is decommissioned.
- Once a leak is suspected, revoke immediately and reissue.
4. Observability
Log the request ID, model identifier, token usage, latency, time to first byte, and error codes; collect them centrally through a logging service, and configure thresholds for error rate, latency, and quota usage together with monitoring alerts, so problems are caught before they affect users.
6. Troubleshooting quick reference
- Works locally but not in production: Usually a difference in egress policy, proxy, or key configuration; start by comparing the environment variables on both sides.
- Occasional truncation: Check
finish_reason; if it is a length limit, raise the limit or rewrite the prompt. - Streaming output arrives all at once: Check whether the request body includes
stream: trueand whether the print statements useflush. - Parameter errors after switching models: Different models do not support exactly the same parameters, so manage each model’s parameter template through configuration; switching should change only the config, not the code.
7. Conclusion
The difficulty of integrating a large model API usually lies not in the first call but in key security, protocol decoupling, and long-term stability. Following the flow in this article, you can complete verification from key preparation to streaming output within a single session. After that, layer on retries, rate limiting, context management, and monitoring alerts to form a reusable integration standard.
If you use Baidu AI Cloud’s large model services, the same approach applies: create an access credential in the console, confirm the base_url and model identifiers against the official documentation, and manage calls through a unified client wrapper. This general pattern helps teams complete the integration at low cost and leaves room for switching models and running canary tests later.
