LLM API Integration Guide: Four Capability Types and a Compliance Checklist
This article explains how to choose and integrate four common LLM API capabilities—web search with deep reasoning, file and image parsing with OCR, web page reading, and speech APIs. It covers parameter checks, common limits, failure handling, citation validation, file upload workflows, data redaction, and logging practices, with implementation notes for engineers and technical leads evaluating API integration options.
Before You Start: Know the Boundaries of the Four Capabilities
LLM providers are extending their APIs from plain-text Q&A to web search, file parsing, web page reading, and speech interaction. Some multi-step workflows can be handled server-side, which simplifies frontend and business code. Before integration, however, you still need to verify parameters, limits, and compliance requirements item by item.
This article is for engineers building AI applications and technical leads evaluating integration options. If your application only handles plain-text Q&A, you can skip the file and speech sections.
Content in angle brackets, such as <model_name>, must be replaced with the real names and values from the official documentation. Interface names, parameter names, prices, limits, and concurrency figures change by version. The limits in the table below are only common types; use the official documentation and the current contract for specific values.
| Capability | Primary use | Confirm before integration | Common limits | Handling failures |
|---|---|---|---|---|
| Web search (including deep reasoning mode) | Answer real-time questions and provide citations | Search tool toggle parameter, streaming support, citation field format | Longer request latency; search count and concurrency caps | Fall back to an offline answer after timeout and note that information may not be current |
| File and image parsing (including OCR) | Upload documents or images and ask questions, or extract text from images | Supported formats, file size and page limits, scanned-document support | Lower accuracy for scans, handwriting, and low-resolution images | Ask the user to change the format or split the file |
| Web page reading | Read the body of a linked page and generate a summary | Whether explicit enablement is required, fetch timeout | Login pages, paywalls, and dynamically rendered pages may block body text extraction | Tell the user the page cannot be read and ask them to paste the content |
| Speech APIs (ASR, TTS) | Speech-to-text and text-to-speech | Audio format and sample rate, single-request duration limit, available voices | Lower accuracy in noisy environments; long audio must be segmented | Ask the user to repeat when recognition confidence is low; show text only if TTS fails |
OCR belongs to image recognition, not speech interfaces. This article discusses it in the file and image section.
Choosing the Right Capability First
Choosing the wrong capability increases both cost and latency. Use the following order:
- If you need real-time public information, use web search.
- If the user has already provided a specific URL, use web page reading.
- If the user uploads private documents or images, use file parsing.
- If the input or output is speech, use speech APIs.
Use one tool per request. For example, reading a page with web page reading and then passing the body to a plain text model is easier to debug than enabling multiple tools at once.
1. Calling Web Search (Including Deep Reasoning Mode)
Deep reasoning is a model reasoning mode, not an independent API capability. When enabled, the model may retrieve information multiple times, increasing search count and single-request latency. During development, treat it as a switch that changes latency and cost, and show a waiting indicator in the UI.
A typical web search flow has four steps.
- Enable the search tool in the request and set a client timeout. The client timeout should cover both the server timeout and network round-trip time. The margin should be based on measured P95 network round-trip time. The 10-second example below is illustrative only; high-latency links need separate measurement and adjustment.
- The model decides whether the current question needs real-time information. This step is handled server-side, and developers cannot precisely control the decision logic. Test with real questions, including questions that do not need web search, to observe unnecessary retrievals.
- The model initiates retrieval, reads the results, and reasons over them.
- The model returns an answer and citations. Before displaying sources, the frontend should check whether links are accessible and retain the original source fields so users can verify them.
The sample code below separates request construction, rate-limit retry, and timeout fallback into independent functions, making it easier to replace provider-specific parameters. The parameter structures for search tools and file parsing tools are different and cannot be mixed.
import osimport timeimport requestsAPI_URL = os.environ["LLM_API_URL"]API_KEY = os.environ["LLM_API_KEY"]SERVER_TIMEOUT = 60 # Server timeout; refer to official documentationCLIENT_TIMEOUT = SERVER_TIMEOUT + 10 # Allowance should be based on measured P95 network round-trip timeMAX_RETRIES = 3RATE_LIMIT_STATUS = 429 # Rate-limit status code; refer to official documentationHEADERS = {"Authorization": f"Bearer {API_KEY}"} # Authentication method; refer to official documentationdef build_payload(question: str, search_enabled: bool) -> dict:payload = {"model": "<model_name>","messages": [{"role": "user", "content": question}],}if search_enabled:# Toggle and other parameters; refer to official documentationpayload["tools"] = [{"type": "<web_search_tool_type>"}]return payloaddef post_with_retry(payload: dict) -> dict:delay = 1for attempt in range(MAX_RETRIES + 1):resp = requests.post(API_URL, headers=HEADERS, json=payload,timeout=CLIENT_TIMEOUT)if resp.status_code == RATE_LIMIT_STATUS and attempt < MAX_RETRIES:time.sleep(delay) # 1 second, 2 seconds, 4 secondsdelay *= 2continueresp.raise_for_status()return resp.json()raise RuntimeError("Retry attempts exhausted")def ask_with_fallback(question: str) -> dict:try:data = post_with_retry(build_payload(question, search_enabled=True))return {"mode": "online", "data": data}except requests.Timeout:# After a timeout, switch to offline mode. The answer must note that information may not be current.data = post_with_retry(build_payload(question, search_enabled=False))return {"mode": "offline", "data": data}
Citation fields need separate validation. Model-returned sources may be empty, have missing fields, or point to expired pages. Filter them before display.
import requestsdef valid_citations(raw_citations: list) -> list:result = []for item in raw_citations or []:url = item.get("<source_link_field>")title = item.get("<source_title_field>")if not url or not title or not url.startswith(("http://", "https://")):continuetry:# Some sites do not support HEAD requests. This check can only exclude obviously invalid links.resp = requests.head(url, timeout=5, allow_redirects=True)if resp.status_code < 400:result.append({"url": url, "title": title})except requests.RequestException:continuereturn result
Design failure handling as follows.
- On rate-limit errors, retry with exponential backoff, up to three retries, doubling the wait each time, for example 1 second, 2 seconds, and 4 seconds. If retries still fail, return “Service is busy, please try again later” to the user.
- After a search timeout, re-request in offline mode and add a note such as “Unable to retrieve the latest information.” This note should be added by server-side code, not left to the model to generate.
- If citations are empty, do not show a sources section, and do not let the model invent sources.
- Log request latency, error codes, whether retrieval was triggered, and fallback count for later troubleshooting and cost estimation. Do not log API keys.
2. File and Image Input
The quality of file parsing depends on the file itself. Clear digital PDFs usually parse well, while scans, photos, and handwritten content have larger errors. Check the following list before integration.
- Supported file formats, file size limits, and page limits, according to the official documentation.
- Whether scanned documents and text in images are supported, and how recognition accuracy varies with image clarity.
- How tables and charts are parsed. Complex layouts may lose row-column relationships, and amounts, dates, and clause numbers in tables need manual review.
- Error information returned when parsing fails, and how to prompt users to change the format or split the file.
- File retention period and whether the provider uses files for model training. Check these item by item against the user agreement and terms of service.
Before upload, remove unnecessary personal information locally, such as ID numbers, bank card numbers, and phone numbers. Even if the provider stores redacted files, the original file may remain locally or in other stages, so redaction should be completed before upload whenever possible.
File parsing usually has two steps: upload the file to obtain a reference, then pass that reference in a message and ask a question. The sample code below uses a file parsing tool, whose parameter structure differs from the search tool in the previous section. The upload endpoint path, request format, and response fields all follow the official documentation.
import osimport requestsAPI_URL = os.environ["LLM_API_URL"]UPLOAD_URL = os.environ["LLM_UPLOAD_URL"] # Upload endpoint; refer to official documentationAPI_KEY = os.environ["LLM_API_KEY"]HEADERS = {"Authorization": f"Bearer {API_KEY}"} # Authentication method; refer to official documentationdef upload_file(path: str) -> str:# Step 1: Upload the file and obtain a file reference. Multipart format follows official documentation.with open(path, "rb") as f:resp = requests.post(UPLOAD_URL, headers=HEADERS,files={"file": f}, timeout=120)resp.raise_for_status()file_ref = resp.json().get("<file_reference_field>")if not file_ref:raise ValueError("No file reference in the upload response; check the response field name")return file_refdef ask_about_file(file_ref: str, question: str) -> str:# Step 2: Pass the file reference in the message, then ask the question. Message structure follows official documentation.payload = {"model": "<model_name>","messages": [{"role": "user","content": [{"type": "<file_content_type>", "<file_reference_field>": file_ref},{"type": "text", "text": question},],}],}resp = requests.post(API_URL, headers=HEADERS, json=payload, timeout=120)resp.raise_for_status()return resp.json()["<answer_content_field>"]if __name__ == "__main__":ref = upload_file("contract.pdf")print(ask_about_file(ref, "List the payment terms in the contract and cite the clause numbers."))
Parsing results should be logged for review. Suggested records include the original file hash, parsing time, model answer, and content shown to the user. For answers involving table numbers, contract clauses, and OCR results, prompt the user to rely on the original document.
3. Web Page Reading
Web page reading is suitable when the user has already provided a specific URL. It reads the body of the linked page and generates a summary. Before integration, confirm whether it must be explicitly enabled and what fetch timeout applies. Login pages, paywalls, and dynamically rendered pages may prevent body text extraction. On failure, tell the user the page cannot be read and ask them to paste the content.
4. Speech APIs
Speech APIs cover ASR and TTS. Before integration, confirm the supported audio format and sample rate, single-request duration limits, and available voices. Recognition accuracy drops in noisy environments, and long audio needs to be segmented. If recognition confidence is low, ask the user to repeat. If TTS fails, display text only.
