LLM-Native Applications and AI Agents: A Practical Development Guide

    A practical guide to building applications around large language models, covering API integration, prompt engineering, reasoning models, agent architecture, tool calling, and retrieval-augmented generation. Learn how to manage credentials, evaluate probabilistic outputs, control cost and latency, and establish safety boundaries for tool-enabled agents.

    1. What Are LLM-Native Applications?

    An LLM-native application uses a large language model as its core reasoning engine, with business workflows designed around the model’s capabilities. Traditional applications typically treat a model as an isolated external API. An LLM-native application instead places the model at the center of decision-making: interpreting user intent, breaking down tasks, selecting tools, and generating results.

    These applications generally share three characteristics:

    1. Natural language is the primary interface. Users do not need to learn fixed interaction paths.
    2. Model outputs are probabilistic. The same input can produce different results, so development requires an evaluation framework rather than relying on a single test.
    3. Model capabilities change across versions. Applications need room for model switching and regression testing.

    Common examples include question-answering systems, document analysis tools, coding assistants, customer support agents, and data analysis assistants.

    To determine whether an LLM-native approach fits a requirement, consider whether the task involves substantial unstructured text, requires flexible semantic understanding, or cannot be fully captured by explicit rules. If deterministic rules or database queries can describe the entire problem, conventional software is usually simpler and more reliable.

    2. Development Environment and API Integration

    2.1 Managing Credentials and Configuration

    API keys are sensitive credentials. Inject them through environment variables or a secrets management service, and keep plaintext keys out of source repositories and logs.

    Use separate keys for development, testing, and production. Set usage limits to reduce potential financial losses if a key is exposed.

    2.2 Wrapping Basic API Calls

    Most model services accept a list of conversation messages containing system instructions, user messages, and assistant messages.

    The application should wrap network requests in a common function to handle timeouts, retries, and exception conversion centrally. The following example is illustrative; consult the relevant API documentation for exact field names.

    1. import os
    2. import json
    3. API_URL = os.environ["LLM_API_URL"]
    4. API_KEY = os.environ["LLM_API_KEY"]
    5. def chat(messages, model, temperature=0.7, max_retries=3):
    6. headers = {
    7. "Authorization": f"Bearer {API_KEY}",
    8. "Content-Type": "application/json",
    9. }
    10. payload = {"model": model, "messages": messages, "temperature": temperature}
    11. last_error = None
    12. for attempt in range(max_retries):
    13. try:
    14. # http_post is an internal HTTP client wrapper that returns a parsed dictionary.
    15. resp = http_post(API_URL, headers, payload, timeout=30)
    16. return resp["choices"][0]["message"]["content"]
    17. except TimeoutError as e:
    18. last_error = e
    19. time.sleep(2 ** attempt) # Exponential backoff
    20. raise RuntimeError(f"Model call failed: {last_error}")

    Retries should apply only to timeouts, rate limits, and transient service errors. Invalid parameters and authentication failures should be reported and logged immediately rather than retried.

    2.3 Tracking Cost and Latency

    Model calls are generally billed according to input and output volume, and longer outputs tend to increase latency.

    Record input length, output length, and elapsed time for each call from the beginning of development. These measurements provide a basis for later decisions about caching, truncation, and model selection.

    3. Prompt Engineering

    Prompt engineering uses carefully designed input text to guide models toward the expected output consistently. It is often a low-cost way to improve results quickly, but it should be systematic rather than a cycle of ad hoc trial and error.

    3.1 Structuring Prompts

    A maintainable prompt typically contains five components:

    • Role: The capacity in which the model should respond.
    • Task: What the model needs to accomplish.
    • Constraints: What the model must avoid or restrict.
    • Input data: The material to process, enclosed in clear delimiters.
    • Output format: Preferably a structured format, such as JSON with fixed fields.
    1. PROMPT_TEMPLATE = """
    2. You are a financial news analysis assistant.
    3. Task: Read the news below and extract the company name, event type, and sentiment.
    4. Constraints:
    5. 1. Base your assessment only on the source text. Do not add information absent from it.
    6. 2. Sentiment must be one of: positive, negative, neutral.
    7. Output: Return only valid JSON with the fields company, event_type, and sentiment.
    8. <news>
    9. {news_text}
    10. </news>
    11. """

    3.2 Examples and Format Validation

    For more complex tasks, include one to three input-output examples in the prompt. This technique, known as few-shot prompting, should cover both typical cases and edge cases.

    Applications must parse and validate structured outputs. If parsing fails, the error can be returned to the model with a request to correct the output. Set a maximum number of correction attempts.

    3.3 Versioning Prompts

    Prompts need version control just as code does. Record the reason for each change, and compare old and new versions against the same evaluation dataset.

    Without evaluation evidence, a prompt revision may simply appear better on a few individual examples.

    4. Reasoning Models and Chain of Thought

    Chain-of-thought prompting encourages a model to break a complex problem into intermediate steps before reaching a conclusion. Step-by-step reasoning can substantially improve accuracy for mathematical derivations, decisions involving multiple conditions, and multistep planning.

    The trade-off is longer output, which increases latency and cost.

    4.1 When to Use Reasoning Capabilities

    Simple classification, extraction, and rewriting tasks usually do not require extensive reasoning. Complex planning, code debugging, and questions that require synthesizing information from multiple sources are stronger candidates.

    Choose models based on their accuracy and cost on an evaluation dataset rather than defaulting to the most capable model.

    4.2 Presenting Reasoning Results

    Intermediate reasoning content can be lengthy and may contain information unsuitable for direct presentation to users.

    A common engineering approach is to separate intermediate reasoning outputs from the final answer: retain available intermediate content in logs for troubleshooting, while returning only the conclusion and necessary supporting evidence to the user.

    5. Designing AI Agent Architectures

    An AI agent is a system that uses a model as its decision-making core and repeatedly cycles through observation, reasoning, and action.

    Unlike a single question-answer exchange, an agent can call tools, read external state, and adjust its next steps based on execution results.

    5.1 Core Components

    A basic agent typically has four components:

    • Planning module: Breaks the goal into steps.
    • Tool set: Provides external capabilities such as querying, computing, and writing.
    • Memory module: Stores conversation history and intermediate results.
    • Execution loop: Repeatedly calls the model, executes tools, and returns results until the task is complete or a termination condition is reached.

    5.2 Example Execution Loop

    1. def run_agent(task, tools, call_model, max_steps=8):
    2. history = [{"role": "user", "content": task}]
    3. for _ in range(max_steps):
    4. reply = call_model(history, tools)
    5. if reply["type"] == "final":
    6. return reply["content"]
    7. tool_name = reply["tool"]
    8. if tool_name not in tools:
    9. raise ValueError(f"Model requested an unregistered tool: {tool_name}")
    10. result = tools[tool_name](**reply["arguments"])
    11. history.append({
    12. "role": "tool",
    13. "content": json.dumps(result, ensure_ascii=False),
    14. })
    15. raise RuntimeError("Maximum step limit reached before task completion; execution stopped")

    Three design choices are worth noting:

    1. The loop has a step limit. This prevents repeated tool calls from continuing indefinitely.
    2. Tools must be registered in an allowlist. The model cannot invoke unauthorized functions.
    3. Tool results are returned in a structured format. This makes them easier for the model to interpret.

    5.3 Safety Boundaries

    Because agents can execute actions, their safety boundaries must be explicit.

    Write operations, financial transactions, and outbound messages should require human confirmation. Validate tool arguments for both type and range rather than trusting model output directly.

    Tool permissions should follow the principle of least privilege: grant only the access needed to complete the current task.

    6. Tool Calling and Protocol-Based Integration

    Tool calling is a standard way for models to interact with external systems. The general workflow has three stages:

    1. The application declares the available tools and their parameter schemas to the model.
    2. The model produces a structured call request when a tool is needed.
    3. The application executes the tool and returns the result to the model.

    6.1 Writing Tool Descriptions

    Models rely on tool descriptions to decide when to call a tool and how to provide its arguments.

    A description should explain the tool’s purpose, appropriate use cases, parameter meanings, and returned data without ambiguity.

    For example, “look up an order” is too vague. A clearer description states that the tool requires an order ID, returns order status and shipping information, and is not intended for refund operations.

    6.2 Why Standardized Integration Matters

    Writing a separate adapter for every external data source and tool becomes expensive as integrations grow.

    A common tool integration protocol allows data sources to be exposed as standardized services. Applications can then discover and invoke capabilities through the protocol, reducing adapter development effort and making authentication and auditing easier to manage consistently.

    Multi-agent collaboration also benefits from standardized communication. Agents exchange tasks and results through a common message structure and describe their areas of capability. This separates task assignment logic from the implementation of individual agents.

    7. Retrieval-Augmented Generation

    Retrieval-augmented generation, or RAG, retrieves relevant content from a knowledge base before the model answers and includes that content in the prompt as supporting material.

    This allows the model to answer using current or proprietary information while reducing unsupported fabrication.

    7.1 Typical Workflow

    A complete RAG workflow includes:

    1. Document chunking.
    2. Embedding generation.
    3. Index creation.
    4. Candidate retrieval.
    5. Result reranking.
    6. Prompt assembly.
    7. Answer generation.
    8. Source citation and traceability.

    Every stage affects the final result. A quality problem at any stage can carry through to the answer.

    7.2 Key Parameters for Chunking and Retrieval

    Chunk size affects both retrieval precision and contextual completeness.

    Chunks that are too small may lose essential meaning. Chunks that are too large may contain irrelevant material that weakens relevance. A common approach is to split documents by paragraphs or headings and include some overlap so that information spanning boundaries is not cut off.

    Retrieval typically returns a set of top-ranked candidates. A reranking model or filtering rules then select the most relevant passages for the prompt.

    Excessively long context increases cost and can distract the model, so the total length of the assembled context should be controlled.

    1. def answer_with_context(question, index, chat_fn, top_k=5):
    2. candidates = index.search(question, top_k=top_k)
    3. context = "\n\n".join(
    4. f"[Source {i + 1}] {c.text}" for i, c in enumerate(candidates)
    5. )
    6. prompt = (
    7. "Answer the question using only the material below. If the material does not "
    8. "contain the required information, state that the answer cannot be determined, "
    9. "and cite source numbers in your answer.\n\n"
    10. f"Material:\n{context}\n\nQuestion: {question}"
    11. )
    12. return chat_fn([{"role": "user", "content": prompt}])

    7.3 Evaluation Metrics

    Evaluate retrieval recall, answer accuracy, and citation accuracy separately.

    Looking only at the final answer does not reveal whether a failure originated in retrieval or generation. Label the document passages that each evaluation question should retrieve, and measure retrieval performance independently.

    8. Background on Inference Efficiency

    Application developers do not need to implement an underlying inference engine, but understanding inference concepts helps them choose suitable models and deployment approaches.

    Key-value caching, or KV caching, is a common optimization used during generative model inference.