LLM API Practical Guide: From Basic Calls to a Secure Vulnerability-Detection Agent

    This guide walks backend engineers through integrating large language model APIs into production systems. It covers how to navigate example repositories, build a minimal client with retry logic, implement complete tool-calling loops, enforce structured outputs, and design a read-only vulnerability-detection agent with strict permission boundaries, audit logging, and evaluation baselines. All code is pseudocode intended to illustrate call structure rather than vendor-specific syntax.

    1. Scope and Boundaries

    This guide is for engineers who can already write basic backend code and are preparing to integrate an LLM into their business systems. The code here is pseudocode that illustrates call structure. Field names, class names, and parameters must be verified against the documentation of the SDK you actually use. References to “example repositories” are generic and do not represent any vendor’s official certification or endorsement; confirm the source and license yourself before use.

    This article does not cover model training, nor does it discuss circumventing platform restrictions. The agent section covers only defensive code auditing and contains no offensive or exploitation steps.

    2. Organizing an Example Repository

    Mature example repositories are usually organized by capability. The table below shows one common layout; actual directory names depend on the repository you use.

    Directory Category Main Content Recommended Starting Point
    Basic integration Key loading, client initialization, first call, streaming output Get one simple request working end to end
    Prompt engineering System prompts, few-shot examples, structured output constraints Learn to specify output format in the prompt
    Tool calling Tool definitions, model-returned call requests, result backfill Understand the full message-turn lifecycle
    Retrieval-augmented generation Document chunking, vector retrieval, cited question answering Validate with a small document set first
    Agent examples Task decomposition, multi-step tool calls, human confirmation Study after tool calling works

    Work through the examples in order. Run each one locally and record inputs, outputs, and latency so you can compare results later.

    3. The Minimal Call: Keys, Client, and Error Handling

    API keys belong only in environment variables or a secrets management service—never in code or version control. The client needs a timeout and limited retries for transient errors. The pseudocode below shows these points.

    1. # Pseudocode: replace LLMClient with the real class name and parameters of your SDK
    2. import os
    3. import time
    4. API_KEY = os.environ["LLM_API_KEY"] # Read from environment variable
    5. client = LLMClient(api_key=API_KEY, timeout=60)
    6. RETRYABLE = {"rate_limited", "server_error", "timeout"}
    7. def call_with_retry(messages, max_retries=3):
    8. for attempt in range(max_retries):
    9. try:
    10. return client.messages.create(
    11. model="your-model-name",
    12. max_tokens=1024,
    13. messages=messages,
    14. )
    15. except ApiError as e:
    16. # Retry only rate limiting, server errors, and timeouts; raise everything else
    17. if e.kind not in RETRYABLE or attempt == max_retries - 1:
    18. raise
    19. time.sleep(2 ** attempt) # Exponential backoff: 1s, 2s, 4s

    Errors need categorized handling. Authentication failures, invalid parameters, and content-policy violations should not be retried—doing so wastes quota and masks real problems. Rate-limit errors should be logged to monitoring, and request frequency should be adjusted based on the wait time indicated in response headers.

    4. The Complete Tool-Calling Loop

    Tool calling involves five steps: define the tool’s input schema; the model returns a call request; validate parameters locally and execute; backfill the result as a tool_result; request the model again to produce the final answer.

    The pseudocode below shows this loop. The loop must have an upper bound to prevent the model from calling tools indefinitely.

    1. # Pseudocode: verify field names against your SDK documentation
    2. TOOLS = [{
    3. "name": "get_weather",
    4. "description": "Get the current weather for a given city",
    5. "input_schema": {
    6. "type": "object",
    7. "properties": {"city": {"type": "string"}},
    8. "required": ["city"],
    9. },
    10. }]
    11. def run_weather_tool(city: str) -> dict:
    12. # Real execution logic, e.g., calling an internal weather service
    13. return {"city": city, "condition": "sunny", "temp_c": 12}
    14. def chat_with_tools(user_text: str, max_steps: int = 5) -> str:
    15. messages = [{"role": "user", "content": user_text}]
    16. for _ in range(max_steps):
    17. resp = call_with_retry(messages)
    18. if resp.stop_reason != "tool_use":
    19. return resp.text
    20. messages.append({"role": "assistant", "content": resp.content})
    21. results = []
    22. for block in resp.content:
    23. if block.type == "tool_use" and block.name == "get_weather":
    24. args = block.input
    25. if not isinstance(args.get("city"), str):
    26. out = {"error": "invalid parameters"}
    27. else:
    28. out = run_weather_tool(args["city"])
    29. results.append({
    30. "type": "tool_result",
    31. "tool_use_id": block.id,
    32. "content": json.dumps(out, ensure_ascii=False),
    33. })
    34. messages.append({"role": "user", "content": results})
    35. raise RuntimeError("Exceeded maximum tool-call rounds; aborted")

    Two things to note. First, treat model-supplied parameters as untrusted input and validate types and ranges locally. Second, when a tool execution fails, feed the error message back to the model instead of letting the program crash—this gives the model a chance to continue another way.

    5. Reducing Integration Fragility with Structured Output

    Whenever a downstream system needs to parse results, have the model output a fixed JSON structure and validate it against a schema. Retry on validation failure, no more than twice. Requests that still fail should go to a manual review queue rather than being force-parsed as free text.

    Keep structured output fields to a minimum, and give each field a clear meaning. Use English for field names; the descriptive content can remain in your working language.

    6. A Vulnerability-Detection Agent: Inputs, Outputs, and Permission Boundaries

    The goal of a vulnerability-detection agent is to help engineers find candidate issues—not to replace code review. Its design focuses on restricting inputs, restricting tools, logging the process, and requiring human confirmation of conclusions.

    6.1 Input Structure

    1. {
    2. "repo_id": "string",
    3. "commit": "string",
    4. "file_path": "string",
    5. "language": "python",
    6. "max_lines": 400
    7. }

    The agent splits tasks by file or function, processing one unit at a time. max_lines limits the context length of a single run; larger files must be split further.

    6.2 Output Structure

    1. {
    2. "findings": [
    3. {
    4. "id": "string",
    5. "file_path": "string",
    6. "line_start": 0,
    7. "line_end": 0,
    8. "category": "string",
    9. "severity": "low|medium|high|critical",
    10. "description": "string",
    11. "suggested_fix": "string",
    12. "confidence": 0.0,
    13. "needs_human_review": true
    14. }
    15. ]
    16. }

    needs_human_review should default to true. Only after human confirmation may false be written to the results store. confidence serves only as a ranking reference, not as a basis for deciding whether to fix.

    6.3 Tool Permission Whitelist

    Tool Permission Restrictions
    read_file Read-only Can only read files within the repository root
    search_code Read-only Restricted to designated scan directories; result count capped
    list_dependencies Read-only Reads lockfiles only; no network requests

    The following must never be granted to the agent: arbitrary shell commands, network access, file writes, and modification of version control state. The agent cannot auto-merge code or auto-commit fixes.

    6.4 Audit Log Fields

    Every run must be recorded in an audit log. Recommended fields: timestamp, run ID, step number, tool name, parameter hash, model version, input and output token counts, reviewer, and review outcome. A parameter hash can replace the original source code, keeping sensitive code out of the logs.

    6.5 Run Workflow

    1. Read the repository file list and filter out test data and generated files by rule.
    2. Invoke the agent unit by unit, passing only that unit’s content each time.
    3. Validate output against the schema; retry at most twice on failure.
    4. Aggregate results and deduplicate by file and line number.
    5. Have engineers review each finding; confirmed items enter the fix pipeline.
    6. After fixes, rerun the agent against the regression test set to confirm the issues are gone and no new false positives appeared.

    7. Engineering and Evaluation Checklist

    7.1 Layered Client Checklist

    • Timeouts: Set connection and read timeouts separately. The values below are starting points and should be adjusted for your network and task length.
    • Retries: Retry only rate limiting, server errors, and timeouts—at most three times, with exponential backoff.
    • Streaming parsing: Handle mid-stream disconnects, keep the partially received content, and mark it as incomplete.
    • Error classification: Record authentication errors, parameter errors, rate limiting, content blocking, and server errors separately for statistics.

    7.2 Evaluation Baseline

    • Sample set: Prepare a set of known-vulnerable samples and a set of clean code, roughly equal in size. Samples must be human-labeled and updated regularly.
    • Metrics: Track recall, precision, and false-positive rate; recompute them after every model or prompt change.
    • Regression gate: A new version’s recall must not fall below the previous version’s. If the false-positive rate rises beyond the team-defined threshold, the change cannot ship. The threshold should reflect the team’s risk tolerance.

    7.3 Pre-Launch Checks

    • All inputs and outputs have schema validation.
    • Tool permissions match the whitelist, with no extra write or network capabilities.
    • Key fields of every run are queryable in the audit log.
    • The regression test set passes on the current version.

    8. Security, Permissions, and Compliance

    Key management is the first line of defense. Store keys in environment variables or a dedicated secrets management service, and rotate them regularly. After rotation, confirm old keys are invalidated and check logs for any leakage.

    Sending code and data externally requires separate approval. Code snippets sent to the model should be sanitized first—remove passwords, tokens, personal information, and internal domain names. The team needs to confirm the data retention and training policies of the service in use and reconcile them with contract terms.

    Log sanitization matters just as much. Logs must not contain full source code, keys, user data, or raw sensitive model output. When troubleshooting, locate records by run ID and hash values.

    Human review cannot be skipped. High and critical findings must be confirmed by an engineer before action. Any agent output is only a candidate conclusion; responsibility for fixes remains with the engineering team.

    Permission isolation must run through the whole system. The account the agent runs under can access only the repositories and tools it needs—never personal admin credentials. Every permission change must be logged and approved by an owner.

    When rolling out, first get the entire pipeline working on a small repository. Confirm logging, evaluation, and review all function properly before gradually expanding scope.