A Complete Guide to Calling LLM APIs from C++
This guide walks C++ developers through calling large language model APIs end to end: the three prerequisites (api_key, base_url, model), OpenAI-compatible authentication and core endpoints, the C++ dependency stack, a working code sample, streaming and multi-turn handling, and production hardening tips. You will learn how to build a stable C++ client for chat, embeddings, and function calling.
1. Why C++ Developers Need a Dedicated LLM Integration Guide
Most mainstream examples of calling large language model APIs use curl, Python, or Node.js. For developers who work in C++, however, ecosystem examples are relatively scarce, and it is easy to get stuck on recurring issues: how to set up the environment, how to assemble JSON, how to send HTTP requests, and how to read streams.
In fact, calling an LLM API does not depend on the language at all. It is built on HTTP/HTTPS, with a JSON request body and a JSON or SSE response body. As long as C++ can construct request headers, serialize JSON, issue an HTTPS request, and parse the response, it is fully capable of the job—and it has natural advantages in low-latency, high-concurrency, and on-device integration scenarios.
Using a cloud provider’s OpenAI-compatible LLM API as the technical background, this article walks through the entire process of calling an LLM from C++: understanding the core interfaces, setting up dependencies, implementing and running complete code, and finally hardening the solution for production.
2. Start With the Essentials: 3 Pieces of Information You Must Have
Regardless of the language, calling an LLM API first requires confirming three key pieces of information. They are the foundation of a successful integration:
- api_key: Obtained after registering an account on the relevant platform. It is the core credential for authentication, equivalent to a temporary password for your account. If leaked, others can use up your quota.
- base_url: The base URL for accessing the model, usually provided in the platform documentation. It looks like
https://<platform-domain>or includes a version path. Whether it includes/v1must be confirmed against the official documentation—this is the most common source of 404 errors for beginners. - model: The model type to call, such as a general-purpose chat model name (for example, naming in the style of
deepseek-chat). Different models may differ in context length, capability focus, and billing.
Keep these three items centralized in a configuration file or environment variables rather than hard-coded in source code, so credentials do not leak along with the repository.
3. Background: Core Interface Logic Under the Compatible Protocol
Since mainstream LLM APIs generally support the OpenAI protocol, understanding its core design first will make the C++ implementation much smoother. The logic boils down to two parts: authentication and interface parameters.
3.1 Authentication: Two Methods, the First Recommended
Every request must carry an api_key to verify identity. Compare the two transmission methods:
- Recommended: Pass it through the HTTP header in the format
Authorization: Bearer <your API Key>. This is more secure and follows standard HTTP semantics. - Alternative: Pass api_key directly in the request parameters. Not recommended, as it easily exposes the key in logs, proxy caches, and browser history.
In C++, always use safe string operations when assembling request headers to avoid crashes or injected extra headers caused by formatting buffer overflows.
3.2 Core Interfaces Explained (Focus on These 3)
The most commonly used interfaces in daily development are the chat, embeddings, and function calling interfaces.
3.2.1 Chat Interface (Core, Most Used)
Used for multi-turn conversations with the model. The core is constructing JSON request parameters in the correct format:
- model (string, required): The model name.
- messages (list[dict], required): Conversation history, where each element contains role and content.
- role (string, optional): One of system (system instruction), user (user), assistant (assistant), or function (function/tool result).
- temperature (float, optional): Randomness, ranging from 0 to 2. 0 is the most deterministic, 2 the most random; default is 1.
- max_tokens (int, optional): Maximum number of tokens to generate; must be below the model’s context limit.
- top_p (float, optional): Nucleus sampling, from 0 to 1; choose either this or temperature to control randomness.
- stream (bool, optional): Whether to return a stream.
- tools (list[dict], optional): Function calling configuration declaring the tools the model can call.
- response_format (dict, optional): Specifies the response format, such as forcing JSON output.
The response mode is determined by stream: non-streaming returns a complete JSON; streaming returns an SSE (Server-Sent Events) stream that outputs incremental content segment by segment, suitable for real-time conversation scenarios.
3.2.2 Embeddings Interface
Takes text as input and returns high-dimensional vectors, commonly used for semantic retrieval, clustering, and deduplication. The key parameters are model and input (a single string or an array of strings). The caller must handle vector storage and similarity computation.
3.2.3 Function Calling Interface
Declare function names, descriptions, and parameter JSON Schema via tools in the request. The model returns a structured call intent, which local code executes and then sends back as a message with role=function, forming a closed loop. This chain is the key to integrating an LLM into a business system.
4. Setting Up Dependencies: Three Pieces of the C++ Puzzle
- Language and build: C++17 or later is recommended, with a general-purpose build tool (such as CMake) for cross-platform support.
- HTTPS client: Choose either a common community libcurl wrapper or Beast based on Boost.Asio. The former is quick to start with; the latter offers more control.
- JSON library: Choose a widely used header-only JSON library, and enable exception and UTF-8 support to ensure Chinese content is not garbled.
You also need TLS dependencies such as OpenSSL, and you must configure the static/dynamic library order correctly at the link stage—this is the most common compile-time error.
5. Complete Code Implementation (Illustrative)
#include <string>#include <iostream>#include <curl/curl.h>static size_t onWrite(char* p, size_t s, size_t n, void* u) {static_cast<std::string*>(u)->append(p, s * n);return s * n;}std::string chat(const std::string& key, const std::string& url,const std::string& model, const std::string& question) {std::string body = R"({"model":")" + model + R"(","messages":[{"role":"user","content":")" + question + R"("}],"stream":false})";std::string resp;curl_global_init(CURL_GLOBAL_DEFAULT);CURL* h = curl_easy_init();curl_easy_setopt(h, CURLOPT_URL, url.c_str());curl_easy_setopt(h, CURLOPT_POST, 1L);curl_easy_setopt(h, CURLOPT_WRITEFUNCTION, onWrite);curl_easy_setopt(h, CURLOPT_WRITEDATA, &resp);curl_easy_setopt(h, CURLOPT_HTTPHEADER, curl_slist_append(nullptr, ("Authorization: Bearer " + key).c_str()));curl_easy_setopt(h, CURLOPT_POSTFIELDS, body.c_str());CURLcode rc = curl_easy_perform(h);curl_easy_cleanup(h);curl_global_cleanup();return rc == CURLE_OK ? resp : std::string("request failed");}
Note: In real projects, use a JSON library to build the request body and avoid string concatenation errors with quotes, newlines, and escaping. Also make the URL, timeout, and retries configurable.
6. Key Details for Streaming Output and Multi-Turn Conversations
- Stream parsing: SSE pushes line by line with a
data:prefix. Buffer by line and parse incrementally, finishing when the end marker arrives. On the C++ side, handle partial and coalesced packets properly. - Multi-turn context: Each turn, append the user and assistant content to messages, and set a context limit. When it is exceeded, summarize or apply sliding-window truncation to control token costs.
- Error handling: Distinguish 401 (wrong key), 429 (rate limiting), and 5xx (server errors). Apply exponential backoff retries for 429 and 5xx.
7. Production Hardening Recommendations
Inject keys through environment variables or a key management service; redact logs and never print full request headers; add timeouts, circuit breaking, and rate limiting to the call chain; feed request and response metrics into logging services and monitoring alerts; if the business involves sensitive data, prefer deployment modes that support data not being persisted. For stronger elasticity and operations capabilities, containerize the calling service on a container platform and use object storage to hold long-text context.
8. Summary
Calling LLM APIs from C++ is not mysterious: hold on to four main threads—the three essentials, header authentication, JSON parameters, and stream parsing—then fill in environment dependencies and production hardening, and you get a stable, usable client. Cloud providers such as Baidu AI Cloud also offer LLM services compatible with common protocols along with supporting cloud product capabilities, so developers can migrate existing code smoothly.
