Building a Device Inspection Script with LLM APIs: A Practical Development Log

    A practical walkthrough of developing a multi-device security inspection script with the help of a large language model API. This article covers authorization boundaries, cost estimation, model integration and verification, and the data collection layer, with manual checkpoints at each step. While an LLM can quickly produce a first draft of the code, authorization confirmation, cost calculation, and boundary testing remain the developer's responsibility.

    This article uses a multi-device security inspection script as an example to document the complete process from model integration to working code. An LLM can quickly generate a first version of the code, but it will not handle authorization confirmation, cost estimation, or boundary testing for the developer. The following sections follow the actual development order, with manual checkpoints listed for each step.

    1. Define Requirements and Boundaries First

    The inspection script needs to cover 9 underlying devices and run on a daily schedule. It performs three tasks: collecting device status and alarm data, writing the cleaned data into Excel, and displaying the day’s results and historical trends through a simple page.

    Before writing any code, confirm three things.

    First, all devices must be owned by you or covered by written authorization. The authorization scope must be clearly defined, including which devices can be accessed, which operations can be performed, and during which time windows.

    Second, the inspection script only performs read-only queries and makes no configuration changes. The collection account uses read-only permissions, not an administrator account.

    Third, credentials must never be written into code, configuration files, or logs. Account passwords and API keys are provided through environment variables or a secrets management service.

    2. Estimate the Cost First

    Before choosing a plan, estimate the monthly cost. The formula is:

    Monthly cost ≈ daily calls × 30 × (input tokens per call ÷ 1,000,000 × input price + output tokens per call ÷ 1,000,000 × output price)

    Here is a hypothetical example. Assume 60 calls per day, with about 3,000 input tokens and 1,000 output tokens per call. That gives roughly 1,800 calls per month, totaling 5.4 million input tokens and 1.8 million output tokens. If the input price is a per million tokens and the output price is b per million tokens, the monthly cost is approximately 5.4a + 1.8b.

    Three points need attention. First, always refer to the pricing published on the official website of the platform you choose, since prices vary significantly across platforms and models. Second, code generation often involves pasting large chunks of API documentation and logs into the context, which noticeably increases input tokens. Third, plans usually limit the number of calls within a time window, such as a cap every 5 hours. Before development, check three things: the call limit within the window, whether overages are billed per token, and the response behavior when rate-limited. Only with these three items confirmed can you judge whether a plan is sufficient.

    3. Model Integration and Verification

    Specific tool names, configuration interfaces, and version numbers should follow the documentation of the tools you use. Regardless of the tool, the core integration steps are the same.

    Step one: create an API key in the platform console and store it as an environment variable. The example below uses placeholders; the real values exist only in your local environment:

    1. export LLM_BASE_URL="https://your-provider.example.com/v1"
    2. export LLM_API_KEY="replace-with-your-key"
    3. export LLM_MODEL="model-id-provided-by-the-platform"

    Step two: reference the environment variable names in the routing tool’s configuration. Do not write the key in plaintext into configuration files, and do not commit configuration files to the code repository.

    Step three: verify connectivity with a minimal request. If the platform is compatible with OpenAI-style APIs, you can test with the following command:

    1. curl "$LLM_BASE_URL/chat/completions" \
    2. -H "Content-Type: application/json" \
    3. -H "Authorization: Bearer $LLM_API_KEY" \
    4. -d '{"model":"'"$LLM_MODEL"'","messages":[{"role":"user","content":"ping"}]}'

    Once a normal response is returned, move on to the code generation stage. Common errors and troubleshooting directions:

    • 401: the key is wrong, or the environment variable has not taken effect in the current terminal.
    • 404: the model ID or the base_url path is incorrect.
    • 429: rate limiting triggered. Reduce the call frequency and add backoff retry on the client side.

    4. The Data Collection Layer

    The collection layer is divided into two categories based on how each device is accessed. Dependency versions need to be pinned in requirements.txt and tested in the actual environment, such as requests, urllib3, selenium, openpyxl, and flask.

    4.1 Devices with APIs

    For devices that provide RESTful APIs, use requests with a retry strategy. The following code limits the timeout and retry count, and only retries idempotent GET requests:

    1. import os
    2. import requests
    3. from requests.adapters import HTTPAdapter
    4. from urllib3.util.retry import Retry
    5. def build_session() -> requests.Session:
    6. retry = Retry(
    7. total=3,
    8. backoff_factor=1,
    9. status_forcelist=[500, 502, 503, 504],
    10. allowed_methods=["GET"],
    11. )
    12. session = requests.Session()
    13. session.mount("https://", HTTPAdapter(max_retries=retry))
    14. return session
    15. def fetch_device_status(session, base_url, timeout=10):
    16. token = os.environ["DEVICE_TOKEN"]
    17. headers = {"Authorization": f"Bearer {token}"}
    18. resp = session.get(f"{base_url}/api/status", headers=headers, timeout=timeout)
    19. resp.raise_for_status()
    20. return resp.json()

    The retries in this code only cover network fluctuations and temporary server-side errors. Business errors returned by the device need to be handled separately at a higher layer.

    4.2 Devices with Only a Web Management Interface

    For devices that only offer a web interface, Selenium can be used to simulate login. The page element IDs below are placeholders only and must be replaced with the actual elements on the real page; each step also requires explicit waits:

    ```python
    import os
    from selenium import webdriver
    from selenium.webd