Large Model API Integration: Tool Calling and Cost Estimation
This article shows how to build an AI assistant prototype with a large model platform's built-in server-side tools, including web search, web page reading, file parsing, and speech recognition and synthesis. It explains how server-side tool calling differs from client-side orchestration, provides a sample request using the OpenAI Python SDK, and covers troubleshooting, a cost estimate based on example prices, and data handling for uploaded files and voice data. The tool names, endpoints, and prices are examples, so check the official documentation and pricing page before use.
This article uses a sample large model platform to show how to build an AI assistant prototype with its built-in server-side tools: web search, web page reading, file parsing, and speech recognition and synthesis. The tool names, endpoints, and prices in this article are examples only. Check the official documentation and pricing page before you start.
How does server-side tool calling differ from client-side orchestration?
In a traditional setup, developers handle the entire tool-calling chain. The model first returns an intent to call a search tool. The client then runs the search and sends the results back to the model, which generates the final answer. Each extra round adds a network round trip and more state to maintain.
With server-side tool calling, these steps run inside the platform. The client declares the available tools in the request. The platform decides whether it needs external information, then performs the search, extracts the content, and assembles the context on its own. The client receives only one response. This significantly reduces client code and the number of network round trips.
This approach has trade-offs. The data source for a search, the pages it fetched, and how long the results are retained are visible only to the extent the platform reports them. If your business requires strict traceability of information sources, first confirm whether the platform returns citation sources.
How do you declare built-in tools in a request?
The following example uses the OpenAI official Python SDK. Install version 1.x (pip install openai). Platforms that support the Chat Completions protocol can usually reuse this code directly. The tool types web_search and read_url are sample names. The actual tool type names, parameter formats, and whether any extra switches are required must be confirmed in the official documentation.
import osfrom openai import OpenAI, APIError, APITimeoutError, RateLimitErrorclient = OpenAI(api_key=os.environ["LLM_API_KEY"], # Read from an environment variable. Do not hard-code it.base_url=os.environ.get("LLM_BASE_URL", "https://api.example-llm.com/v1"),timeout=30.0, # Includes server-side tool execution time. Leave enough margin.max_retries=2,)def ask(question: str) -> str:try:response = client.chat.completions.create(model="your-model-name", # Replace with a model that supports tool calling, per the platform documentationmessages=[{"role": "system", "content": "You are a concise assistant. Include the date or time of any information in your answers."},{"role": "user", "content": question},],tools=[{"type": "web_search"}, # Example: web search. Confirm the type name in the documentation.{"type": "read_url"}, # Example: web page reading. Confirm the type name in the documentation.],)except APITimeoutError:return "The request timed out. Please try again later."except RateLimitError:return "Too many requests or insufficient quota. Please check your quota."except APIError as e:return f"The platform returned an error: {e}"return response.choices[0].message.contentif __name__ == "__main__":print(ask("What's the weather in Beijing today? Is it good for outdoor exercise?"))
Some platforms offer parameters such as disabling deep thinking. You can pass these through extra_body if the platform supports them. Check the documentation to confirm. When you first integrate, run print(response.model_dump_json(indent=2)) to inspect the full response. If the platform returns tool call details, the field names may be tool_calls or a custom field. Use the actual response to determine the field names. Do not write parsing code based on guesses.
How do you troubleshoot errors?
| Symptom | Possible cause | Troubleshooting step |
|---|---|---|
| The answer has no up-to-date information | The tool was not triggered because the model decided no search was needed | Explicitly ask for an online lookup in the question, and check whether the platform accepted the tools declaration |
| The request times out | Server-side fetching took too long | Increase timeout, or reduce the number of tools in a single request |
| Error 429 or a quota error | The request rate or account balance exceeded the limit | Check usage in the console, and configure retries with exponential backoff |
| A parameter error for a tool type | The type name or format does not match the documentation | Compare each field against the official example, and print the full response |
| The answer does not match the web page content | The fetched page was outdated or the extraction was incomplete | Save the source URLs returned by the tool, and spot-check them manually |
What makes up the billing?
Billing on this platform typically has two parts. Base model usage is charged by the number of input and output tokens, and the unit price may differ between peak and off-peak hours. Add-on tools are charged per call or by duration. For example, search may be charged per 1,000 calls, and speech recognition and synthesis may be charged by audio duration. Promotional discounts often have expiration dates, so check the applicable period when you estimate costs.
The following example uses hypothetical unit prices to demonstrate the calculation method. These numbers do not reflect the actual pricing of any platform.
Assumptions:
- 60,000 conversation requests per month
- 800 input tokens and 300 output tokens per request
- 50% of requests trigger one web search, and 10% trigger one web page read
- Assumed unit prices: input CNY 2 per million tokens, output CNY 8 per million tokens, search CNY 10 per 1,000 calls, web page reading CNY 5 per 1,000 calls
Results:
- Input: 60,000 × 800 = 48 million tokens, totaling CNY 96
- Output: 60,000 × 300 = 18 million tokens, totaling CNY 144
- Search: 60,000 × 50% = 30,000 calls, totaling CNY 300
- Web page reading: 60,000 × 10% = 6,000 calls, totaling CNY 30
- Monthly total: about CNY 570, or about CNY 0.0095 per request on average
The search trigger rate is the most sensitive variable. If the trigger rate rises from 50% to 100%, search costs increase from CNY 300 to CNY 600, and the monthly total rises to about CNY 870. Measure your actual trigger rate before launch, then build your budget.
For high-frequency real-time information, such as weather and sports scores, you can cache the final answer on the client. The cache key consists of the question text and key parameters, such as the city. Set the time to live (TTL) based on how often the information updates. For example, use 30 minutes for weather and 5 minutes for news. Also track the cache hit rate to confirm that the cache actually reduces the number of calls.
What should you watch for with uploaded files and voice data?
Uploaded images, PDFs, and voice recordings often contain personal information, such as ID numbers, bank card numbers, and medical records. Handle them with the following practices:
- Mask or redact sensitive fields before uploading.
- Obtain explicit user consent, and state the purpose and retention period of the files in your privacy policy.
- Confirm with the platform how long data is stored, whether it is used for model training, and whether you can delete data on request.
- Voice data may contain biometric features such as voiceprints. Handle it according to the regulations of the region where you operate.
- Validate the type and size of uploaded content to keep malicious files out of your processing pipeline.
- Keep processing logs in your own system, but do not write raw file content to them.
What should you do before launch?
- Build a test set of at least 100 real business questions. Record the tool trigger rate, answer accuracy, and average latency.
