A Practical Guide to Calling LLM APIs from C++: From Protocol Basics to Production-Ready Code
This article provides a comprehensive walkthrough for C++ developers who need to integrate large language model (LLM) APIs without relying on official SDKs. It explains the underlying HTTP/HTTPS + JSON communication protocol, covers authentication and core request parameters, and demonstrates a complete non-streaming chat completion implementation using libcurl and nlohmann/json. It also addresses error handling, timeout strategies, and common pitfalls such as encoding issues, delivering a clear path toward building robust, production-ready AI service clients in C++.
Understanding the Core of LLM API Calls
Calling large model APIs is becoming a foundational capability in AI application development. While different platforms provide SDKs in various languages, the underlying communication mechanism is highly uniform: HTTP/HTTPS requests with JSON payloads, using RESTful endpoints to obtain structured responses. For C++ developers, there may be no official SDK in the ecosystem, but by understanding the protocol, you can efficiently connect using common libraries like libcurl and nlohmann/json.
Three Essential Prerequisites
Regardless of programming language, calling an LLM API requires the following:
- Authentication credential: the API Key, typically obtained after registering on the provider’s website. It identifies every request and must be stored securely—never hard-code it in frontend code or public repositories.
- Base URL: the foundational endpoint to which API paths are appended. Different services have different URL rules, but they universally use HTTPS.
- Model identifier: the model name that determines which version and capabilities are used. Chat models, embedding models, and image generation models each have distinct identifiers.
Engineering suggestion: During project initialization, inject these three parameters via environment variables or configuration files rather than embedding them in source code. This separates environments and reduces the risk of key leakage.
The Design Logic of the OpenAI-Compatible Protocol
Most mainstream open-source or commercial LLM APIs follow the OpenAI-compatible protocol. The elegance of this protocol is that it abstracts complex model inference into three core interfaces: chat completions, embeddings, and function calling.
From a low-level perspective, the protocol does not care what programming language the client uses. It only requires two things:
- Request headers carry authentication using the format
Authorization: Bearer <API_KEY> - Request bodies follow a JSON Schema including top-level parameters like
modelandmessages
This design is naturally language-agnostic, so C++ faces no fundamental difficulty compared to other languages—the key lies in constructing HTTP requests and parsing JSON correctly.
Core Interfaces and Parameter Deep Dive
Two Ways to Pass Authentication
| Method | Mechanism | Security Level | Use Case |
|---|---|---|---|
| Header (recommended) | Via HTTP request headers | High | Default for production |
| Query parameter | Appended to the URL | Low | Local debugging only; vulnerable to leakage |
Why prefer the header approach? Header information does not appear in proxy logs or browser history, and with HTTPS the entire header is encrypted, reducing the risk of man-in-the-middle attacks.
Chat Completions: Required and Optional Parameters
Required Parameters
model(string): specifies the model to use, e.g.,deepseek-chatfor a chat-focused model. Different models have different context lengths and capabilities.messages(list[dict]): maintains multi-turn conversation history. Each element containsroleandcontent. Therolevalues determine the conversation direction:system: sets the model’s behavior and style, e.g., “you are a rigorous technical advisor”user: user inputassistant: model’s historical replies, used to maintain context in multi-turn conversations
Optional Parameters (Enhancements)
| Parameter | Type | Range | Description |
|---|---|---|---|
temperature |
float | 0~2 | Controls randomness. Lower values yield more deterministic output (good for code generation); higher values increase creativity (good for copywriting) |
max_tokens |
int | model-specific limit | Caps generated tokens to prevent resource waste. Note: tokens are not characters—Chinese text consumes roughly 1.5–2 tokens per character |
top_p |
float | 0~1 | Nucleus sampling. Use either temperature or top_p; modifying both simultaneously can cause unpredictable output |
stream |
bool | - | Enables streaming via SSE protocol, returning tokens incrementally. Reduces perceived time-to-first-token |
response_format |
dict | - | Enforces output structure, e.g., {"type": "json_object"} forces the model to emit valid JSON |
Embeddings and Function Calling
- Embeddings interface: converts text into high-dimensional vectors—a fundamental building block for knowledge-base retrieval and semantic similarity matching. Typically accepts an array of strings and returns an array of vectors.
- Function calling: allows developers to define a set of executable tools; the model automatically selects the relevant function and generates a JSON argument object based on the user’s intent. This capability is key to building agentic applications, marking a shift from “generating text” to “driving actions.”
Setting Up the C++ Environment and Dependencies
The most common stack for C++ HTTP calls:
- libcurl: the most mature HTTP client library, supporting HTTPS, POST, and custom headers
- nlohmann/json: a modern C++ JSON library that provides Python-dict-like access syntax
- OpenSSL: transport-layer dependency for libcurl to ensure encrypted HTTPS communication
Installation Examples
Ubuntu/Debian:
sudo apt updatesudo apt install libcurl4-openssl-dev nlohmann-json3-dev
macOS (local development):
brew install curl nlohmann-json
Windows: Use the vcpkg package manager; a single command installs all dependencies.
Compilation and Linking
g++ -std=c++17 main.cpp -o client -lcurl -lssl -lcrypto
Note: You must explicitly link curl and the SSL libraries, otherwise you will encounter undefined reference errors.
Complete Non‑Streaming Chat Implementation
Full Code (~150 lines)
#include <iostream>#include <string>#include <curl/curl.h>#include <nlohmann/json.hpp>using json = nlohmann::json;using namespace std;// Callback function: appends response chunks to the bufferstatic size_t WriteCallback(void* contents, size_t size, size_t nmemb, string* buffer) {buffer->append((char*)contents, size * nmemb);return size * nmemb;}// Constructs and executes the chat completion requeststring chat_completion(const string& api_key, const string& base_url,const string& model, const json& messages) {CURL* curl = curl_easy_init();if (!curl) {return "{\"error\":\"curl init fail\"}";}string response;string url = base_url + "/chat/completions";json payload = {{"model", model},{"messages", messages},{"temperature", 0.7},{"max_tokens", 2048},{"stream", false}};struct curl_slist* headers = nullptr;headers = curl_slist_append(headers, "Content-Type: application/json");headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());curl_easy_setopt(curl, CURLOPT_URL, url.c_str());curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.dump().c_str());curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);curl_easy_setopt(curl, CURLOPT_TIMEOUT, 60L); // Timeout protection// Enable SSL certificate verification (required in production)curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L);CURLcode res = curl_easy_perform(curl);if (res != CURLE_OK) {response = "{\"error\":\"" + string(curl_easy_strerror(res)) + "\"}";}curl_slist_free_all(headers);curl_easy_cleanup(curl);return response;}// Extracts the text content from the response bodystring extract_content(const string& response_body) {auto json_resp = json::parse(response_body);if (json_resp.contains("choices")) {return json_resp["choices"][0]["message"]["content"];}if (json_resp.contains("error")) {return "API Error: " + json_resp["error"].value("message", "unknown");}return "Empty response";}int main() {// Read sensitive information from environment variablesconst char* api_key = getenv("LLM_API_KEY");string base_url = "https://provider-api.example.com/v1"; // Replace with actual Base URLstring model = "your-chat-model-id";if (api_key == nullptr) {cerr << "Please set the LLM_API_KEY environment variable" << endl;return 1;}json messages = json::array();messages.push_back({{"role", "system"},{"content", "You are a C++ code review expert."}});messages.push_back({{"role", "user"},{"content", "Please write a generic quicksort template function in C++ and point out potential performance bottlenecks."}});string resp = chat_completion(api_key, base_url, model, messages);cout << "Model reply: " << extract_content(resp) << endl;return 0;}
Key Code Explanations
- Callback function mechanism: libcurl writes data blocks to memory incrementally via the callback, avoiding memory spikes from large responses.
- JSON serialization: the
dump()method converts structured data into a string, ensuring a valid request body. - Timeout setting: LLM inference often takes time, especially non-streaming. Setting a 60‑second timeout is a sensible safety net against permanently hanging threads.
- Modular function decomposition: separating request construction, execution, and parsing makes it easy to later extend the code with streaming or other API types.
Engineering Pitfalls and Error Handling
Network‑Level Error Classification
| CURL Error Code | Typical Cause | Mitigation |
|---|---|---|
CURLE_COULDNT_CONNECT |
DNS failure, port unreachable | Check network connectivity and Base URL spelling |
CURLE_OPERATION_TIMEDOUT |
Model inference exceeds timeout | Increase timeout threshold or enable streaming |
CURLE_SSL_* |
Certificate verification failure | Disable verification only for internal tests; never in production |
Business‑Level Status Code Strategy
- 401 Unauthorized: invalid API Key. First verify that the environment variable is loaded correctly.
- 429 Too Many Requests: rate limiting triggered. Implement exponential backoff with retry.
- 400 Bad Request: JSON Schema mismatch. Print the request body in logs for inspection.
Chinese Character Encoding Pitfall
String literals in C++ source code must be UTF‑8 encoded for HTTP transmission. If your project uses GBK, convert the string to UTF‑8 before constructing the request body; otherwise the model’s reply might contain garbled text or be truncated.
Summary and Expansion Directions
With the workflow above, C++ developers can bypass SDK dependencies and call LLM APIs directly through the underlying protocol. This capability is especially valuable in:
- Embedded or desktop applications that cannot run a Node.js or Python runtime
- Low-latency gateway layers that require precise control over HTTP connection pooling and concurrency
- Cross-platform SDK development that needs a unified C++ core for other languages
Future improvements could focus on: enabling stream: true for SSE parsing, using CURLOPT_MULTI_PERFORM for multithreaded concurrent requests, and decoupling response handling from business logic to build a reusable AI service client class.
General recommendation: For production use, wrap the API call layer into a standalone library, exposing only simple interfaces such as SendPrompt() and ProcessStreamData(), so that upper‑layer business code remains unaware of network details. This not only marks engineering maturity but also is essential for building robust systems.
