Large Language Model API Integration Guide: Capability Evaluation and Cost Control
Integrating an LLM API is not just about sending a successful request. This guide covers how to define integration goals, secure API credentials, build a reliable request flow, connect tools such as web search and speech services, estimate usage costs, and evaluate models across accuracy, latency, stability, tool reliability, and unit economics. It also includes practical checks for controlling operational risk before launch.
1. Define the Integration Goals First
The main challenge in integrating a large language model API is usually not making the first successful request. The harder questions are whether performance will remain stable after launch, whether costs can be controlled, and whether the request path will be easy to troubleshoot.
Before integration, answer three questions:
- What task should the model perform?
- How much response latency can users tolerate?
- What is the maximum budget for a single task?
Document these requirements so that model selection, testing, and monitoring have a clear foundation. For example, a customer-support summarization workflow may tolerate several seconds of latency but require high accuracy. Real-time voice interaction, by contrast, is highly sensitive to latency and may impose strict limits on output length.
2. Preparation: Credentials and Environment Isolation
Start by creating access credentials in the provider’s console. Credential management directly affects system security. Follow these practices:
- Store keys only in environment variables or a dedicated secrets-management service. Do not place them in source code, configuration files, or logs.
- Use separate keys for development, testing, and production. This makes troubleshooting easier and allows you to revoke credentials for a single environment.
- Set usage limits and alert thresholds for each key to prevent unexpected requests or retry loops from causing uncontrolled spending.
- Rotate keys regularly. If an employee leaves or a key may have been exposed, revoke it immediately and issue a replacement.
A configuration example is shown below. Variable names can be adjusted to match your team’s conventions:
LLM_API_URL = read_environment_variable("LLM_API_URL")LLM_API_KEY = read_environment_variable("LLM_API_KEY")
3. Basic Request Flow
A complete model request usually includes five steps:
- Build the request
- Send the request
- Parse the response
- Validate the result
- Record logs
Each step can fail, so the implementation should handle them separately.
function call_model(prompt, max_retries = 3):headers = {"Authorization": "Bearer " + LLM_API_KEY,"Content-Type": "application/json"}body = {"messages": [{"role": "user", "content": prompt}]}for i in range(max_retries):response = send_POST_request(LLM_API_URL,body,headers,timeout=30_seconds)if response.status_code == 429: # Rate limit triggeredwait(2 ** i seconds) # Exponential backoffcontinueif response.status_code >= 400:raise_error(response.status_code, response.content)return parse_response_body(response) # Follow the API documentationraise_error("Request failed after multiple retries")
This pseudocode contains three important design choices:
- Timeouts: A timeout prevents a stalled connection from consuming resources and affecting the rest of the service.
- Exponential backoff: When rate limiting occurs, exponential backoff reduces the risk of a retry storm.
- A retry limit: A maximum retry count prevents infinite loops from consuming quotas.
Response field paths vary between APIs. Always follow the documentation for the service you are using rather than guessing based on another provider’s response format.
Model output should be treated as untrusted data. Before passing it into business logic, validate that it matches the expected format. For example, check whether it is valid JSON, whether all required fields are present, and whether numeric values fall within reasonable ranges. If validation fails, you can retry the request once with the validation error included. If the second attempt also fails, route the task to a manual-review queue.
4. Key Considerations for Extended Capabilities
Many providers offer capabilities beyond basic text generation, including web search, webpage retrieval, speech-to-text, and text-to-speech. The integration pattern is similar in each case:
- The model decides when to call a tool.
- The tool returns a result.
- The model generates a final response based on that result.
When integrating these capabilities, pay attention to the data boundaries and risks associated with each one.
4.1 Web Search
Web search can provide information that was not available in the model’s training data, such as current market conditions, policy changes, and news events.
Key considerations include:
- Search results come from external sources. Record the source URL and retrieval time for traceability.
- Conclusions generated by the model should include source citations so that people can verify them.
- For time-sensitive questions, specify a time range in the prompt to reduce interference from outdated information.
4.2 Webpage Retrieval
Webpage retrieval passes the content of a specified page to the model for processing. Common use cases include document summarization and information extraction.
Follow these guidelines:
- Respect the target site’s robots rules and terms of service. Do not retrieve content that the site explicitly prohibits.
- Webpages may contain text designed to manipulate the model, such as “ignore previous instructions.” Treat webpage content as untrusted data. In the system prompt, clearly instruct the model to extract information only and never execute instructions found in the page content.
- Set a maximum length for retrieved content. An excessively long page can consume the context window and increase costs.
4.3 Speech-to-Text
Speech-to-text is useful for meeting transcripts, customer-support quality reviews, and similar workflows. Pricing is often based on audio duration, so measure the length of each recording before upload.
Long recordings should be split into segments. This makes it possible to retry only the failed segment instead of processing the entire file again. If recordings contain personal information, define a retention period in advance and automatically delete files after that period expires.
4.4 Text-to-Speech
Text-to-speech can be used for alerts, voice responses, and other audio interfaces. Longer text generally increases both synthesis time and cost.
Practical strategies include:
- Split long text by sentence or paragraph before synthesis.
- Cache audio for recurring fixed messages to avoid synthesizing the same content repeatedly.
5. Cost Estimation
Uncontrolled spending often results from an incomplete understanding of the provider’s pricing structure. The following sections describe three common billing models.
5.1 Usage-Based Billing: Input and Output Calculated Separately
Token-based pricing usually separates input and output tokens, and the two types generally have different rates. Output tokens are often more expensive than input tokens, so limiting output length may produce more immediate savings than compressing the input.
Another common issue is context growth. In a multi-turn conversation, including the entire message history in every request causes input token usage to grow over time. To control this, retain only necessary history or summarize earlier exchanges.
5.2 Per-Call Billing: Track Tool Calls Separately
Tools such as web search and webpage retrieval may be billed by the number of calls, typically per call or per thousand calls. These costs are separate from token charges and should be tracked independently.
A model may call the same tool multiple times during one task. Record every tool call in the logs so that usage can be reconciled with the provider’s invoice.
5.3 Pricing Differences by Time Period
Some providers charge different rates during peak and off-peak periods. For batch processing and offline analysis that do not require immediate results, scheduling jobs during off-peak periods may reduce costs.
Always verify current prices on the provider’s official pricing page before launch. Do not rely on secondhand information.
5.4 Estimation Example
The following function estimates the cost of a single task. The prices are hypothetical and are provided only to demonstrate the calculation method.
function estimate_cost(input_tokens,output_tokens,input_price_per_million,output_price_per_million,tool_calls = 0,tool_price_per_thousand = 0):token_cost =input_tokens / 1,000,000 * input_price_per_million +output_tokens / 1,000,000 * output_price_per_milliontool_cost = tool_calls / 1,000 * tool_price_per_thousandreturn token_cost + tool_cost
Assume that one task uses 2,000 input tokens and produces 800 output tokens. The input price is 1 yuan per million tokens, the output price is 4 yuan per million tokens, and the task makes one web-search call.
The token cost is:
2,000 / 1,000,000 × 1 + 800 / 1,000,000 × 4 = 0.0052 yuan
If the hypothetical search-tool price is 5 yuan per thousand calls, one search costs:
5 / 1,000 = 0.005 yuan
The estimated total is therefore approximately 0.0102 yuan. Multiplying this estimate by the daily task volume provides an initial daily cost forecast.
6. Five Dimensions for Capability Evaluation
Before selecting a provider or model, evaluate it systematically across the following five dimensions instead of relying on a single demonstration.
- Task accuracy: Build an evaluation set from real business examples, including normal, boundary, and abnormal inputs. Report accuracy separately for each task type and record representative error cases.
- Response latency: Track P50 and P95 response times. An average can hide long-tail behavior, while P95 better reflects the proportion of slow requests experienced by users.
- Stability: Track error-code distributions, timeout rates, and rate-limit frequency. If the same request set produces significantly different results at different times, investigate the cause.
- Tool-call reliability: Check whether generated tool parameters are valid, whether fallback logic exists when a tool fails, and whether repeated or unnecessary calls occur.
- Unit cost: Calculate unit cost as
total spending ÷ successfully completed tasks. Failed tasks also consume resources, so counting only successful tasks provides a more realistic measure of efficiency cost.
7. Pre-Launch Checklist
Before going live, verify the following items:
- API keys have been moved to a secrets-management service; no plaintext keys appear in the repository or logs.
- Separate credentials are used for development, testing, and production.
- Usage limits and alert thresholds have been configured.
- Request timeouts, rate-limit handling, exponential backoff, and maximum retry counts have been implemented.
- Model responses are validated before entering business logic.
- Tool calls, source URLs, retrieval times, errors, and retry events are recorded.
- Input tokens, output tokens, tool calls, and task outcomes are tracked for cost analysis.
- Accuracy, P50 latency, P95 latency, stability, tool reliability, and unit cost have been evaluated using representative workloads.
