Building a Personal Assistant and Coding Agent with LLM APIs: A Practical Architecture Guide

    This article walks through two common integration patterns for large language models: a long-running personal assistant connected to messaging platforms, and a terminal-based coding agent. It covers a layered assistant architecture, unified message formats, model call wrappers with retries, context trimming, agent execution loops with step limits, command whitelisting for security, and stability practices such as timeouts, circuit breakers, and usage monitoring—complete with runnable Python examples and a deployment checklist.

    1. The Real Problem: Integrating Models into Actual Workflows

    Tutorials on integrating large language models are everywhere, and the most common question readers ask is “which entry point should I choose?” But entry points are only a surface-level difference. What truly determines the experience is how the model works with messaging channels, code environments, data storage, and permission systems. Rather than discussing any specific product, this article abstracts two general scenarios—a long-running personal assistant and a terminal-based coding agent—and explains the technical principles they share.

    2. The Layered Architecture of a Personal Assistant

    A personal assistant that runs over the long term typically consists of five layers:

    1. Message ingestion layer: receives messages from instant messaging platforms, usually via webhook callbacks or long polling.
    2. Session management layer: maintains conversation history by user or session ID, and truncates or summarizes context.
    3. Model invocation layer: encapsulates request construction, retries, timeouts, and error handling.
    4. Capability extension layer: connects external capabilities such as calendars, notes, and retrieval through tool calls.
    5. Persistence and monitoring layer: stores session and task state, and logs invocations and runtime metrics.

    The benefit of layering is that any layer can be replaced without affecting the others. For example, migrating the messaging channel from one platform to another only requires rewriting the ingestion adapter, while session and model invocation logic stay unchanged.

    2.1 A Unified Internal Message Format

    Message structures vary significantly across platforms. The recommended approach is to define a unified internal format first, then let each platform adapter handle conversion. Business logic then only deals with a single data structure.

    1. from dataclasses import dataclass
    2. @dataclass
    3. class IncomingMessage:
    4. channel: str # Source channel name, e.g., "im_channel_a"
    5. user_id: str # Platform-specific user identifier
    6. session_id: str # Session identifier, used to link conversation history
    7. text: str # Normalized plain-text content

    The adapter’s job is to map raw platform events into this structure and discard fields irrelevant to the conversation. Attachments, emoji reactions, and quoted content in raw events should be handled separately in the adapter, not passed directly to the model.

    2.2 A Minimal Model Invocation Wrapper

    Model services typically expose conversational capabilities through HTTP APIs. The request body generally contains a message list, a model identifier, and sampling parameters. Field names and response structures depend on the specific service’s documentation; the example below isolates these differences in a few lines so they are easy to adjust later.

    1. import os
    2. import time
    3. import requests
    4. API_URL = os.environ["MODEL_API_URL"]
    5. API_KEY = os.environ["MODEL_API_KEY"]
    6. MODEL_NAME = os.environ.get("MODEL_NAME", "")
    7. def call_model(messages, max_retries=3, timeout=30):
    8. headers = {"Authorization": f"Bearer {API_KEY}"}
    9. payload = {"model": MODEL_NAME, "messages": messages}
    10. for attempt in range(1, max_retries + 1):
    11. try:
    12. resp = requests.post(API_URL, json=payload, headers=headers, timeout=timeout)
    13. resp.raise_for_status()
    14. # The parsing path should be adjusted based on your service's response docs
    15. return resp.json()["choices"][0]["message"]["content"]
    16. except requests.RequestException:
    17. if attempt == max_retries:
    18. raise
    19. time.sleep(2 ** attempt) # Exponential backoff to avoid hammering the service

    This code reflects three engineering principles: secrets are read from environment variables, never hardcoded; every request sets a timeout; and failures are retried with exponential intervals, with the exception propagated upward on the final failure.

    2.3 Context Trimming Strategy for Conversations

    Unlimited context growth causes two problems: rising request costs, and the model’s attention being diluted by early, irrelevant content. A common approach is to keep the system instructions and the most recent turns, replacing older content with a summary.

    1. def trim_history(messages, keep_last=20):
    2. system_msgs = [m for m in messages if m["role"] == "system"]
    3. dialog_msgs = [m for m in messages if m["role"] != "system"]
    4. return system_msgs + dialog_msgs[-keep_last:]

    The number of retained turns should be tuned to the actual task. A casual chat assistant can retain fewer, while tasks that span multiple days need to be paired with a summarization mechanism that writes key facts into persistent storage.

    3. How a Terminal Coding Agent Works

    The core loop of a coding agent is: understand the task, read the code, devise a modification plan, apply changes, run tests, and iterate based on the results. Compared with ordinary Q&A, it has two additional requirements. First, it needs access to the file system and command line, so permission boundaries must be explicit. Second, it must locate problems from failed test output, so the information returned by tools must be complete and readable.

    3.1 An Execution Loop with a Step Limit

    An agent can fall into a loop of repeatedly modifying the same piece of code. Setting a step limit is the most basic safeguard.

    1. def agent_loop(task, max_steps=20):
    2. history = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = call_model(history)
    5. action = parse_action(reply) # Parse model output into a structured action; implement per your tool protocol
    6. if action["kind"] == "finish":
    7. return action["summary"]
    8. observation = execute_tool(action) # Execute the tool and capture output; implement per your tool protocol
    9. history.append({"role": "assistant", "content": reply})
    10. history.append({"role": "tool", "content": observation})
    11. raise RuntimeError("Max steps exceeded; task incomplete, manual intervention required")

    The parse_action and execute_tool functions in this example need to be implemented according to your specific tool-calling protocol. The key point: when the limit is reached, the agent must fail explicitly rather than silently return something that looks like success.

    3.2 Basic Principles of Task Decomposition

    Complex tasks should be decomposed first, then executed step by step. Three principles apply: each subtask has a clear completion criterion; dependencies between subtasks are explicitly recorded; and each step’s scope of change is kept as small as possible for easy rollback and review. For example, “fix a null-pointer issue in an API” can be split into five steps: reproduce the problem, locate the code, write the fix, add tests, and run the full test suite.

    4. Security Boundaries: Least Privilege

    An agent that can execute commands means a wrong instruction can cause real damage. Security design should deny by default and only open explicitly allowed capabilities.

    4.1 Command Whitelisting

    1. import subprocess
    2. ALLOWED_COMMANDS = {
    3. "unit_tests": ["python", "-m", "unittest", "discover"],
    4. "list_files": ["ls", "-la"],
    5. }
    6. def run_allowed(name: str) -> str:
    7. if name not in ALLOWED_COMMANDS:
    8. raise PermissionError(f"Command not in whitelist: {name}")
    9. result = subprocess.run(
    10. ALLOWED_COMMANDS[name],
    11. capture_output=True,
    12. text=True,
    13. timeout=300,
    14. check=False,
    15. )
    16. return result.stdout + result.stderr

    The whitelist is stored as a mapping from names to fixed argument lists; the model can only choose a name, not assemble arbitrary arguments. This prevents command injection. Any parameters involving user input should also be validated or escaped before use.

    4.2 Treat External Content as Data

    Web pages, message bodies, and file contents may all contain text disguised as instructions. The system must treat such content as data, not as instructions to execute. For irreversible operations—deleting files, pushing code, sending messages externally—require human confirmation, and display the full content of what will be executed before confirming.

    4.3 Secret Management

    Access keys for model services should be injected via environment variables or a dedicated secret management service, and never written into code, configuration repositories, or logs. When logging requests, sanitize request headers and user privacy fields.

    5. Stability and Cost Control

    A long-running assistant will face all kinds of anomalies. Common risks include network jitter, rate limiting, response timeouts, and runaway costs.

    • Timeouts and retries: all external calls set timeouts and use exponential backoff with a capped number of retries.
    • Circuit breaking and degradation: after consecutive failures hit a threshold, pause calls and return a clear status message to users instead of letting requests pile up.
    • Usage tracking: record request counts and token usage per session and per user, set daily budget thresholds, and trigger alerts or throttling automatically when exceeded.
    • Structured logging: log request IDs, latency, status codes, and error types for later troubleshooting, while avoiding sensitive content in logs.

    Monitoring metrics should include at least success rate, average response time, number of calls per task, and daily cost. These data points help teams decide where to optimize—for example, whether to compress context or adjust retry strategy.

    6. Deployment Checklist

    • Secrets are injected via environment variables or a secret management service; no plaintext keys in code or logs
    • All external calls have timeouts, with capped retries and backoff intervals
    • Context has a truncation or summarization mechanism, keeping history length under control
    • Agent commands and tools use whitelists, with a step limit in place
    • High-risk operations (deletion, pushing, outbound messaging) require human confirmation
    • External content is treated as data, not executed as instructions
    • Logs are sanitized and record request IDs and error types
    • Monitoring and alerting are configured for success rate, response time, and cost

    An assistant and coding agent built on this structure will have clear boundaries, observable runtime behavior, and controllable costs. Teams can start with a single channel and a single task type to validate the interface and permission design of each layer, then gradually expand to more scenarios.