LLM Tool APIs in Practice: Building an AI Assistant with Tool Calling, Cost Control, and Compliance

    This article explains how to integrate LLM platform tool capabilities—web search, deep-thinking search, file parsing, link reading, and independent APIs such as search, web scraping, OCR, and speech recognition/synthesis—into a conversational AI assistant. It covers capability differences, a sample request structure, billing and cost-control strategies, caching and architecture design, security and compliance requirements, and a pre-launch checklist to help developers ship reliable tool-calling assistants with less rework and risk.

    A major LLM platform has recently opened up a set of tool capabilities, including web search, deep-thinking search, file parsing, and link reading, plus standalone APIs for search, web scraping, OCR, and speech recognition and synthesis. Developers can wire these capabilities into a conversation flow to build an AI assistant with functionality close to that of a native client. The actual experience depends on the chosen model, the tool combination, and network conditions, so it may not fully match the native client. This article explains how to call these capabilities, how they are billed, and how to stay compliant, and it ends with an actionable checklist.

    1. Capability Overview

    The inputs, outputs, and prerequisites of each tool differ significantly, so verify each item before integration.

    Capability Input Output Prerequisites Billing Basis Fallback on Failure
    Non-thinking web search User question Answer with cited sources Enable the search tool in the request Billed per search On search failure, return an answer without citations and note that information may be outdated
    Deep-thinking search Complex questions Answer after multi-step reasoning Select a model that supports deep thinking and enable the corresponding mode Model tokens plus search and reading call fees Reduce reasoning steps or fall back to the normal mode
    File parsing PDFs, Office documents, images Structured text and tables File size and format within platform limits Billed per parsed page On parsing failure, prompt the user to re-upload or convert the format
    Link reading Webpage URL Webpage content summary Link must be publicly accessible Billed per fetch On fetch timeout, explain that the page could not be read

    Field names, toggle mechanisms, and limits are defined differently across platforms. This table only describes the general logic; refer to the official documentation of each platform for specific parameters.

    2. Request Structure and Example

    A request typically includes the model name, the message list, and tool switches. The example below only illustrates the structure—the endpoint, model name, and tool fields are placeholders that have not been verified against official documentation and must not be used directly in production.

    1. import requests
    2. API_ENDPOINT = "<API endpoint from the official documentation>"
    3. API_KEY = os.environ["MODEL_API_KEY"] # Read the key from environment variables, never hardcode it
    4. payload = {
    5. "model": "<model name from the official documentation>",
    6. "messages": [{"role": "user", "content": "<user input>"}],
    7. "tools": "<tool list declared in the official format>",
    8. }
    9. try:
    10. resp = requests.post(
    11. API_ENDPOINT,
    12. headers={"Authorization": f"Bearer {API_KEY}"},
    13. json=payload,
    14. timeout=(5, 60), # Set connection timeout and read timeout separately
    15. )
    16. resp.raise_for_status()
    17. answer = resp.json()["choices"][0]["message"]["content"]
    18. except requests.Timeout:
    19. answer = "The service timed out. Please try again later."
    20. except requests.RequestException:
    21. answer = "The service is temporarily unavailable. The error has been logged."

    Note that os must be imported in real code. Error details should be written to logs, but never log API keys or raw user input.

    3. Billing and Cost Control

    Costs consist of two parts: model token fees and tool call fees. The former is based on input and output text volume; the latter on the number of tool invocations or their duration.

    Match billing metrics to your business volume:

    • Search: billed per call. Daily searches × unit price equals the search cost.
    • File parsing: billed per page. Pages per file × per-page price, summed across files.
    • Speech: billed by duration. Convert audio seconds into billing units and multiply.

    Unit prices are subject to the platform’s published pricing. It is recommended to set budget alerts—for example, notify the owner when daily spend reaches 80% of the daily budget, and suspend non-core tool calls at 100%.

    There are three common ways to reduce costs. First, intent routing: use rules or a small model to determine whether a question needs external information, and only enable web search when necessary. Second, result caching: cache search results for queries with low freshness requirements, with an expiry time. Third, parsing reuse: parse each file only once and store the result keyed by the file content hash.

    4. Architecture and Cache Design

    A typical architecture includes a frontend interaction layer, a gateway/scheduling layer, a business logic layer, and a model service layer. The business logic layer handles three things: controlling context length, managing caches, and handling retries.

    File parsing results are well suited to session-level or persistent caching. The cache key can combine the file content hash with a parsing version number, so the cache automatically invalidates when either the file content or the parsing rules change. Link reading results can also be cached, but with a shorter expiry because web content changes quickly.

    When the context grows too long, prioritize truncating older tool results while keeping the user’s questions and the most recent answers. After truncation, preserve the indexes of citation sources so that citations in the answer still resolve correctly.

    Retry policies should distinguish error types. Network timeouts and server-side 5xx errors can be retried a limited number of times with exponential backoff. Parameter errors and authentication failures should not be retried; return the error directly.

    5. Security and Compliance

    The platform’s built-in safety check parameters can intercept some non-compliant inputs and outputs, but they do not replace your own compliance responsibilities.

    Files uploaded by users and links they submit are personal or sensitive data, so define clear retention periods and deletion policies. A common practice is to keep the original files only for the minimum necessary period after parsing and delete them automatically afterward; when a user requests deletion, synchronously clean up caches and logs. The specific retention period should be determined based on your business scenario and applicable regulations.

    Apply masking in logs: fields such as phone numbers, ID numbers, and bank card numbers should be replaced with masks before being written.

    For public-facing services, add a second layer of content moderation beyond the model itself. When the model returns a refusal flag, or the input hits sensitive-word rules, trigger a manual or independent review process.

    Before launch, complete any LLM-related registrations or filings required by the regulations in your jurisdiction. The frontend should prominently label content as AI-generated and inform users that they are interacting with an AI system.

    6. Pre-Launch Checklist

    1. Tool switch parameters match the official documentation and have been validated in a test environment.
    2. Billing trigger conditions for each tool are documented, and budget alerts are configured.
    3. Timeouts, retry counts, and fallback messages are defined, and error scenarios are covered by tests.
    4. Cache keys, expiry times, and invalidation rules are clearly specified.
    5. Retention periods and deletion processes for uploaded files and links are documented in the privacy notice.
    6. Log masking rules are in effect, and no API keys appear in code or logs.
    7. Trigger conditions and handling procedures for the second-layer review are confirmed.
    8. Registrations, filings, and AI-content labeling are complete.

    7. Conclusion

    Tool capabilities lower the barrier to building AI assistants, but calling parameters, costs, caching, and compliance still need to be handled item by item. Before integration, check the official documentation, validate each tool’s behavior with test data, and launch according to the checklist—this reduces rework and risk.