LLM Agents and Long-Context Practice

    A practical guide to building LLM agents that execute tasks, not just complete chats: capability bounds, a planning-execution-memory-observation architecture, office and engineering workflows, function-calling loops, long-context discipline, and governance.

    Large language models are shifting from chat completion to task execution. Users once asked whether a model could write or answer; they now ask whether it can keep a goal consistent over a long context, call external tools by a stable protocol, and fold documents, tables, and screenshots into one workflow. The work is not chasing each model release. It is treating reasoning, memory, tools, and evaluation as an engineering system. This article covers capability judgment, system design, typical scenarios, and constraints for production.

    Clarify capability bounds before “what can run automatically”

    An agent lands in production only if three conditions hold at once: knowledge and reasoning are stable enough, the context window covers real task span, and tool calls are predictable.

    On knowledge and reasoning, “near top closed-source quality” usually means error rates on multi-step planning, code edits, document synthesis, and constraint satisfaction can be absorbed by process—not that a single output is perfect. Gaps between open-source and commercial APIs show up more in stability, tool-protocol completeness, and long-context decay than in “can it chat.”

    On context, million-token windows are discussed as a future default. Engineering meaning: you can put repo-scale code, policy files, meeting notes, and historical tickets in one session and avoid loss from chunk-then-summarize. A larger window is not stronger memory. Attention dilution, later text overwriting facts, and higher cost and latency are real. Treat long context as a searchable workbench, not an unbounded dump.

    On tools, function calling turns text generation into action selection. Interfaces must be rigid: names, parameter schemas, error codes, timeouts, and idempotency. The model decides when to call, which tool, and how to fill parameters. The runtime owns auth, quotas, audit, and rollback. Mix those roles and the agent is uncontrollable in production.

    A layered architecture: planning, execution, memory, observation

    A single giant prompt is hard to maintain. Four layers are more durable.

    Planning. Split the user goal into verifiable subtasks with success criteria. For “turn last week’s sales report into an exec summary,” success is complete fields, consistent definitions, and traceability to source tables—not elegant prose.

    Execution. Each subtask maps to a tool class: read object storage, query a database, call an internal approval API, run a script in a container, write a document. Prefer fine-grained tools for retries and least privilege.

    Memory. Short-term: session context. Mid-term: task-level summaries. Long-term: retrieval (vector or keyword) plus structured profiles. Long windows fit a single task’s full materials, not permanent raw history in the prompt. Policies, API docs, and metric definitions should be versioned knowledge items, not one-off pastes.

    Observation. Log every plan, tool call, and human confirmation. Logs, alerts, and tracing answer what the model saw, why it chose a tool, and whether the result was accepted. Without observation you cannot iterate or pass compliance.

    On the cloud, put raw inputs and outputs in object storage, decouple long jobs with a message queue, run stateless executors on containers, and use unified identity for secrets and access control—never put keys in the prompt.

    Office automation: four reusable scenarios

    Multi-source weekly reports. Inputs: table exports, meeting notes, email bullets. The agent checks fields and date ranges, fills a fixed template, and lists conclusions that cannot be inferred from sources. Do not invent numbers; mark gaps and request missing files.

    Policy and contract review. Put current policy and the draft in one context. Output a diff: conflicting clauses, missing obligations, vague language. Every finding needs a source locator for legal or business confirmation. Long context reduces the risk that a section disappears in a summary.

    Form fill from screenshots and scans. Vision brings invoices, ticket screenshots, and UI into the same pipeline. Extract fields with a vision model, validate format and required fields with rules, write through workflow. Humans handle low-confidence or conflicting fields. Do not give the model production write access.

    Repo-scale engineering help. Million-token context makes “read a whole module then change one place” feasible, still with tests and static checks. The agent proposes a patch; the pipeline runs unit and integration tests; humans review high-risk paths. An agent is an accelerator, not a bypass of quality gates.

    The shared pattern: the model understands and drafts; the system constrains and persists; humans confirm the critical steps. Stronger automation means later confirmation points and less repetitive work, not unattended operation.

    How this differs from “knowledge-base Q&A” products

    The market often compares systems that “read many documents and write a report.” One class is notebook-style knowledge with citations. Another is agent-like: many tools, many steps, write-back to business systems. Both have value; engineering focus differs. The first optimizes retrieval, citation trust, and reading experience. The second optimizes planning stability, tool protocol, permissions, and failure recovery. Choose by whether the job is “understand and cite” or “finish and write back.” Merging both into one super-prompt usually fails at both.

    Minimal closed loop for function calling

    You do not need a heavy framework. Close the loop first:

    1. Define tools: one JSON Schema per tool—types, enums, required fields, and side-effect level (read-only / write).
    2. The model emits a structured call; the runtime validates the schema and rejects extra fields.
    3. Execute and return a compact result: not the whole table, only rows or aggregates for the current subgoal.
    4. Recoverable errors: timeout, insufficient permission, empty data as machine-readable errors so the model can retune parameters or escalate to a human.
    5. Stop conditions: success criteria met, step budget exceeded, or consecutive failures—halt instead of looping.

    Illustrative flow (names are generic, not vendor-specific):

    1. user_goal -> planner.decompose()
    2. loop:
    3. call = model.select_tool(schema, state)
    4. result = runtime.invoke(call) # auth, timeout, audit
    5. state = memory.update(result)
    6. if done or budget_exceeded: break
    7. human_review(state.artifacts)

    Stabilize call format before polishing prompts. Evaluation should cover: should-call vs skip, wrong tool, out-of-range parameters, and forgotten constraints in long context.

    Discipline for long context

    After windows grow, the common misuse is stuffing unrelated logs, duplicate attachments, and stale policies. Three rules: trim by task relevance; tag each document with title, time, and authority; for huge repos use “directory + expand on demand,” not one-shot ingest of every file. Cost, latency, and privacy (personal data in the session) belong in the design, not as afterthoughts.

    Risk and governance

    Agents amplify execution and mistakes. Write tools need second confirmation or canary rollout. Filter prompt injection and poisoned tool results at runtime. Content that goes external needs sensitivity and fact checks. Governance is not another system prompt; it is permissions, audit, quotas, and human gates. Treat model calls as ordinary microservices: unified identity and key management, network isolation, and operational audit.

    Conclusion

    Building LLM agents is not chasing a release. It is wiring long context, function calling, multimodal input, and office process into a system you can observe and roll back. Define success criteria first, then layer planning, execution, memory, and observation, and lock capability in with evaluation and permissions. Automation then becomes repeatable productivity rather than a one-off impressive output.