Building a Full-Featured AI Assistant with Application-Layer APIs: A Practical Guide
LLM providers now expose web search, link reading, file parsing, speech interaction, and content moderation as APIs, making it possible to assemble a working AI assistant without separately integrating a search engine, vector database, OCR, or speech modules. This article explains the boundaries of each capability, walks through a complete Function Calling loop, and covers error handling, cost estimation, and a pre-launch checklist.
Recently, LLM providers have begun exposing capabilities such as web search, link reading, file parsing, and speech interaction as APIs. Developers no longer need to separately integrate a search engine, a vector database, OCR, and speech modules to assemble a usable AI assistant. These capabilities are convenient, but their boundaries, costs, and failure modes differ significantly. This article explains, from an engineering perspective, how to integrate them and what to verify before going live.
1. Understand the Boundaries of Each Capability First
1.1 Web Search
The model can proactively initiate retrieval before generating an answer. It decides whether a search is needed, generates search queries, and organizes the results, which reduces errors caused by relying solely on training data. However, the freshness, coverage, and source quality of search results depend on the provider’s index. Questions involving internal data or non-public information cannot be answered by the search tool.
1.2 Link Reading
The link reading tool fetches a target web page, extracts the main content, and converts it into text the model can process. It works well for news, technical documentation, and long-form reading. Pages behind paywalls, pages that require login, and heavily dynamically rendered sites often yield no useful content, so the business side needs to detect these cases.
1.3 File Parsing and OCR
PDFs, Word documents, and scanned images can be used directly as input. OCR recognizes the text first, then hands it to the model for organization and Q&A. Recognition quality is good for clean printed documents. With handwriting, low-resolution scans, tables, and content obscured by stamps or seals, recognition errors propagate directly into the answers. Key fields in invoices and contracts should be validated with rules or reviewed manually.
1.4 Speech Input and Synthesis
Speech-to-text (STT) turns user speech into prompts, and text-to-speech (TTS) reads the answers aloud. Both have duration or concurrency limits; long recordings should be handled as asynchronous tasks.
1.5 Content Moderation
Moderation tools can block policy-violating content in the conversation flow. They may also block legitimate content by mistake, so blocked results should be logged and made available for manual review rather than silently discarding the request.
2. Running a Complete Call with Function Calling
Most providers are compatible with the Chat Completions format, and tools are declared via the tools parameter. After reading each tool’s name, description, and parameter structure, the model decides whether to call it. The parameter structure is described with JSON Schema; without it, the model cannot generate valid arguments.
The code below is pseudocode and cannot run directly. The client address, model ID, and built-in tool type names must all be replaced with the actual values from the provider’s documentation.
# Pseudocode, not directly runnable. Replace placeholders such as YOUR_BASE_URL# and YOUR_MODEL_ID with values from the provider's documentation.import jsonimport osfrom openai import OpenAI # Assumes a Chat Completions-compatible provider; use the official SDK per documentationclient = OpenAI(api_key=os.environ["LLM_API_KEY"], base_url="YOUR_BASE_URL")MODEL = "YOUR_MODEL_ID"tools = [{"type": "function","function": {"name": "web_search","description": "Search the web for the latest public information. Use this tool for time-sensitive questions.","parameters": {"type": "object","properties": {"query": {"type": "string", "description": "Search keywords"},},"required": ["query"],},},},{"type": "function","function": {"name": "read_url","description": "Fetch and parse the main content of a given web page.","parameters": {"type": "object","properties": {"url": {"type": "string", "description": "A complete http or https URL"},},"required": ["url"],},},},]def run_tool(name, args):"""Implement yourself: must include timeout control and exception handling, and return a serializable result."""raise NotImplementedErrormessages = [{"role": "user", "content": "Search for the latest cloud computing trends and summarize the key points of this link: https://example.com/tech-trends"}]# First round: the model decides whether to call toolsfirst = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)msg = first.choices[0].messagemessages.append(msg.model_dump(exclude_none=True))# Execute the tools and send results back as tool messagesfor call in (msg.tool_calls or []):try:args = json.loads(call.function.arguments)result = run_tool(call.function.name, args)except Exception as e:result = {"error": str(e)}messages.append({"role": "tool","tool_call_id": call.id,"content": json.dumps(result, ensure_ascii=False),})# Second round: the model generates the final answer based on tool resultsif msg.tool_calls:second = client.chat.completions.create(model=MODEL, messages=messages, tools=tools)print(second.choices[0].message.content)else:print(msg.content)
This code demonstrates the standard two-round loop. In the first round, the model returns tool_calls; the client executes the tools and sends the results back as messages with the tool role. In the second round, the model generates the final answer based on the tool results. Some providers execute built-in tools server-side, so the client only receives the final answer—no custom execution or feedback logic is needed. Before integrating, confirm which category your tools belong to.
3. Error Handling and Degradation
Any link in the tool-calling chain can fail. Common cases include: the model’s arguments not being valid JSON, tool timeouts, unreachable URLs, OCR timeouts, or provider rate limiting. Recommended handling:
- Argument parsing failure: Log the raw content and send the error message back as a tool message so the model can reorganize the call. Retry at most once.
- Tool timeout: Set explicit timeouts. After a timeout, tell the user the information is temporarily unavailable and provide a partial answer based on what is already available.
- Rate limiting: Retry with exponential backoff plus random jitter. After exceeding the retry limit, queue the request or degrade to answering without web access.
- Unreachable URL: Return the specific reason—for example, DNS resolution failure or a login-required page—and do not let the model fabricate page content.
- Moderation false positives: Keep a summary of the blocked request and the triggered rules for manual review.
All degradation paths should be disclosed in the answer so users know whether the information source is complete.
4. Estimating Costs: Per-Token and Per-Call Billing
Billing typically has two parts: model token fees and tool call fees. Model fees are priced separately for input and output tokens, and some providers offer off-peak discounts. Tool fees may be charged per call, per minute of audio, or per page, and some products have limited-time promotions.
The following template can be used to estimate monthly costs. All unit prices must be taken from the provider’s official price list; no specific figures are given here.
Monthly cost ≈ daily requests × 30 × [ (average input tokens ÷ 1,000,000) × input unit price + (average output tokens ÷ 1,000,000) × output unit price + average search calls × per-search price + average link-reading calls × per-read price + average speech minutes × per-minute price ]
Two things to watch when estimating. First, web search and link reading inject fetched content into the context, which can significantly increase input tokens—counting only the user’s question length will underestimate costs. Second, off-peak batch processing suits non-real-time tasks such as overnight batch document parsing; real-time user conversations should still be budgeted at peak pricing. A good practice is to sample real traffic for one week and then refine the estimate.
5. Pre-Launch Checklist
- Keep API keys only in environment variables or a key management service—never in code or logs.
- Set timeouts, retry limits, and failure-degradation strategies for each tool.
- Log request IDs, model IDs, token usage, tool call counts, error codes, and latency, while redacting user-uploaded content.
- Store files in object storage first, and give the model pre-signed URLs with short expiration times.
- Set up cost alerts that notify the owner when daily usage exceeds the budget threshold.
- Apply rule-based validation to key fields in OCR results, such as amounts, dates, and ID numbers.
- Move long-running tasks (long audio transcription, batch OCR) into a message queue for asynchronous processing.
Conclusion
Application-layer APIs lower the barrier to building an AI assistant, but they do not replace engineering work. Capability boundaries, failure paths, and cost structures all need to be understood before integration. Validating the core pipeline with small traffic first and then gradually expanding usage is generally safer than a full-scale launch all at once.
