Guide to Integrating LLM APIs: Long Context, Prompt Caching, and Agent Practices
Large Language Model (LLM) APIs have become the core infrastructure for building intelligent applications. Over the past two years, their capabilities have expanded from simple chats to long document comprehension, structured outputs, and external tool integration. However, as capabilities grow, challenges related to cost, latency, and stability have also become more prominent. This guide explores API interface compatibility, long context windows, prompt caching, structured output, agent capabilities, and practical use cases, concluding with a reference code example and a pre-launch checklist.
Large Language Model (LLM) APIs have become the fundamental infrastructure for enterprises building intelligent applications. Over the past two years, API capabilities have expanded from single-turn conversations to long document comprehension, structured outputs, and external tool calling. Along with enhanced capabilities, issues related to cost, latency, and stability have also become more prominent. This article explores API interface compatibility, long context, caching billing, structured output, Agent capabilities, and practical use cases, ultimately providing a referenceable integration code and a checklist.
1. Unify the Calling Layer: Carefully Check API Compatibility
Most mainstream API services support Chat Completions style interfaces, and some are also compatible with the Messages style. A unified interface specification reduces migration costs. Developers usually only need to change the Endpoint URL and API Key to switch between locally deployed models, open-source models, and commercial cloud models.
Interface compatibility does not mean identical behavior. Different service providers vary in their support for fields like stream, response_format, and tools, and the chunking format for streaming output may also differ. Before switching, verify the following item by item:
- Whether request fields are supported, especially parameters related to structured output.
- The end markers and incremental field names for streaming responses.
- The return format for tool calls, including whether parameters are in JSON string format.
- The meanings of error codes and rate-limiting responses.
Some cloud platforms quickly provide hosted services upon the release of new models. Specific launch times, available regions, latency, and Service Level Agreements (SLAs) are subject to the official documentation of the service providers. When making selections, base your decisions on actual stress-testing data rather than just promotional descriptions.
2. Long Context: Stronger Capabilities but Cost and Boundaries Must Be Calculated
The context window of LLM APIs has evolved from 32K to 128K, and now to the million-token level. Some models already support even longer inputs. With longer windows, developers can reduce some chunking and retrieval steps, for example, by directly placing a short operation manual or a complete code module into the request.
However, the nominal length of the context window does not equal the effective length. In practice, you need to evaluate the following points:
- Token Cost: The longer the input, the higher the billing per request.
- Response Latency: Longer inputs usually result in higher Time To First Token (TTFT).
- Effective Window: The range of information the model can stably utilize may be smaller than the nominal value; key information placed in the middle is especially prone to being ignored.
- Massive Corpora: Hundreds of documents or an entire code repository still require retrieval, segmentation, or summarization as fallbacks.
In practice, a hybrid strategy can be adopted. Place high-frequency, stable, and moderately sized materials directly into the context, and let the retrieval module filter massive corpora before sending them to the model. This approach balances cost, latency, and accuracy.
3. Caching Mechanism: Reducing the Cost of Repetitive Input
Prompt Caching is an optimization provided by service providers. When the beginning parts of multiple requests are exactly the same, the server can reuse the previously computed prefix, thereby reducing TTFT and lowering the billing for input tokens.
Cache hits usually depend on the following conditions:
- The prefix content must be exactly identical, including spaces and line breaks.
- The prefix length must exceed the minimum number of tokens specified by the service provider.
- The request must fall within the valid cache period.
Caching is an optimization method and does not guarantee a hit for every request. Billing rules also vary by provider; some services price cached hits and missed inputs differently. Specific rules are subject to the official billing documentation.
A practical approach is to place fixed content at the beginning of the message, such as system prompts, tool definitions, and product knowledge bases, while placing the user’s dynamic input later. If you put a timestamp or user ID at the beginning, the cache will almost never be hit.
How to verify if caching is effective? You can read the usage field in the response. The field name differs across providers, and some return the number of cached tokens. It is recommended to log the cache hit rate into monitoring metrics and aggregate it daily or by business line.
4. Peak/Off-Peak Pricing and Batch Scheduling
Some services adjust prices by time period; the unit price during peak hours may differ significantly from off-peak hours. This pricing mechanism is suitable for scheduling tasks with low real-time requirements to off-peak hours.
Specific operations can be divided into three steps:
- Check the Pricing Table: Confirm the unit price of the current model across different time periods, and whether cache hits, cache writes, and regular inputs are priced separately.
- Prioritize Tasks: Keep real-time conversations online; place tasks like offline data cleaning, batch summarization, and batch annotation into a queue.
- Scheduled Execution: Batch consume the queue during low-price periods and set rate limits to avoid triggering throttling due to instantaneous concurrency.
Before rolling out the scheduling plan, use small batches of tasks to verify whether the actual bill matches the estimate.
5. Structured Output and Function Calling
To make the model’s output directly usable by programs, APIs provide several capabilities.
Function Calling: The model outputs function names and parameters based on user intent, and the program decides whether to execute them. This is the foundation for building Agent workflows. Note the following when using it:
- Model output parameters must be validated, including type, value range, and permission checks.
- Do not directly execute model output as instructions, especially for operations like deletion, money transfers, or sending messages.
- Include a manual confirmation step for sensitive operations.
JSON Output: You can constrain the model to return JSON data matching a specified structure, reducing the instability of using regular expressions to parse free text. However, JSON output may still have missing fields or formatting errors, so it requires Schema validation, and retries or fallback handling upon parsing failure.
FIM (Fill-in-the-Middle): The model predicts missing middle parts based on the code before and after the cursor, suitable for real-time completion in code editors. The interface format and support range for FIM vary by provider and must be confirmed before integration.
6. Web Search and File Input
Web Search and Web Scraping: When the model determines its knowledge is insufficient, it can trigger a search and read web content if configuration permits. Confirm the following before integration:
- Whether the account has permission for this capability enabled.
- Whether the billing method is per-call or per-token.
- Whether there are call frequency limits.
- Whether the returned content meets compliance requirements and whether source links are retained in the response.
File Input: Some services support directly uploading files like PDF, Word, and Excel. Standard text-based PDFs can be parsed directly, saving the effort of building your own parsing service. However, scanned documents, complex tables, and specially formatted files still require OCR or dedicated parsing tools. Before uploading, also check file size and format limits, and confirm whether the file contains personal or sensitive data to avoid violating privacy compliance.
7. Typical Scenario Practices
Intelligent Customer Service: Customer service systems can place user interaction history and product knowledge bases into the context, and query business interfaces like orders and inventory via Function Calling to complete closed-loop services. High-frequency standard questions can be prioritized for matching local FAQs, only invoking the model when no match is found, reducing both cost and latency.
Code Assistance: FIM handles real-time prompts within the editor. Cross-file analysis is limited by context length and effective window; it is recommended to prioritize placing files directly related to the current changes. Generating unit tests, code review comments, and bug localization suggestions can be done by the model, but results require manual review, especially for security and business logic.
Scientific Research Assistance: Researchers can upload multiple papers for the model to write literature reviews, and supplement the latest data via web search. Generated citations must be verified against the original texts one by one to prevent the model from fabricating sources.
8. Solution Selection and Cost Estimation
Depending on your needs, you can refer to the table below to choose a solution.
| Dimension | Long Context Direct Input | Retrieval-Augmented Generation (RAG) | Model Fine-tuning |
|---|---|---|---|
| Applicable Materials | Moderately sized, relatively stable documents | Massive, frequently updated knowledge bases | Fixed format, fixed style tasks |
| Per-request Cost | Linear growth with input length | Low retrieval cost, but index maintenance required | High training cost, inference cost depends on model |
| Knowledge Update | Must bring new content with each request | Just update the index | Requires retraining |
| Main Risks | Insufficient effective window, high latency | Retrieval missed recalls or noise | Overfitting, high maintenance cost |
Monthly cost can be roughly estimated using the following formula:
Monthly Cost ≈ Daily Avg Requests × 30 × [Avg Input Tokens × Input Unit Price + Avg Output Tokens × Output Unit Price − Cache Savings]
Where unit prices are subject to the provider’s current price list. When estimating, take the average based on the request distribution of actual business, and reserve a buffer for peak traffic.
9. Integration Code Example
The following Python example demonstrates the basic implementation of a streaming call. The example includes: reading the API key from environment variables, setting connection and read timeouts, implementing exponential backoff retries for 429 and 5xx errors, skipping non-JSON SSE lines, and masking the API key in logs.
import jsonimport loggingimport osimport timeimport requestslogging.basicConfig(level=logging.INFO)logger = logging.getLogger("llm_client")API_URL = os.environ["LLM_API_URL"]API_KEY = os.environ["LLM_API_KEY"]MODEL = os.environ.get("LLM_MODEL", "your-model-name")def _mask(text: str) -> str:"""Hide the API key in logs to prevent leakage."""return text.replace(API_KEY, "***") if API_KEY else textdef call_llm_stream(prompt: str, max_retries: int = 3, timeout=(5, 60)) -> str:headers = {"Content-Type": "application/json","Authorization": f"Bearer {API_KEY}",}payload = {"model": MODEL,"messages": [{"role": "system", "content": "You are a professional code assistant."},{"role": "user", "content": prompt},],"stream": True,}for attempt in range(1, max_retries + 1):try:with requests.post(API_URL,headers=headers,json=payload,stream=True,timeout=timeout,) as resp:if resp.status_code == 429 or resp.status_code >= 500:raise requests.HTTPError(f"Retryable status code: {resp.status_code}", response=resp)resp.raise_for_status()parts = []for raw in resp.iter_lines(decode_unicode=True):if not raw or not raw.startswith("data:"):continuedata = raw[len("data:"):].strip()if data == "[DONE]":breaktry:chunk = json.loads(data)except json.JSONDecodeError:logger.warning("Skipping non-JSON SSE line")continuechoices = chunk.get("choices") or [{}]delta = choices[0].get("delta") or {}text = delta.get("content") or ""parts.append(text)print(text, end="", flush=True)return "".join(parts)except requests.RequestException as e:logger.error("Request %d failed: %s", attempt, _mask(str(e)))if attempt == max_retries:raisetime.sleep(2 ** attempt)return ""# Before running, set the environment variables LLM_API_URL and LLM_API_KEY. Do not hardcode keys in the script.# call_llm_stream("Please write a quicksort algorithm in Python.")
A few points to note in the code. First, when using stream and response_format simultaneously, confirm whether the service provider supports this combination; the example omits response_format for brevity. Second, retries should only target recoverable errors; parameter errors and authentication errors should fail directly to avoid invalid repeated requests. Third, if the business requires a complete JSON output, parse and perform Schema validation after the stream ends.
10. Integration Checklist
Before going live, confirm the following items:
- API keys are stored in environment variables or secret management services, and do not appear in code repositories or logs.
- Each request has both connection and read timeouts set.
- 429 and 5xx errors use exponential backoff retries, with a maximum retry count configured.
- Rate limits and concurrency caps are configured.
- Logs record essential request metrics.
