AI Agents Explained: A Practical Guide to Building LLM-Based Agents
This guide walks through the fundamentals of AI agents, from core concepts and technical architecture to development environment setup and prompt engineering best practices. You will learn about agent types, the four core modules (planning, memory, tools, and execution), mainstream design patterns such as ReAct and Plan-and-Execute, a minimal function-calling code example, and structured prompt frameworks like ICIO and CO-STAR—everything you need to start building your own LLM-based agents.
AI Agents Explained: A Practical Guide to Building LLM-Based Agents
1. What Is an AI Agent?
1.1 Definition
An AI agent is an intelligent system that can perceive its environment, plan autonomously, and invoke tools to complete complex tasks. Unlike traditional one-shot Q&A applications built on large language models, an agent operates in a “think—act—observe—think again” loop: after receiving a user goal, it breaks the goal down into subtasks, executes them step by step, and dynamically adjusts its strategy based on intermediate results until the task is complete. This autonomy is the key leap that turns LLM applications from “chat assistants” into “task executors.”
1.2 Types of AI Agents
Based on capability and interaction style, agents are commonly categorized as follows:
- Conversational agents: Centered on natural language interaction, combined with knowledge bases to handle Q&A, customer support, and guided assistance.
- Task-oriented agents: Focused on specific business workflows—such as automated report writing, data processing, and code generation—with an emphasis on multi-step execution.
- Tool-using agents: Built around function calling, orchestrating external APIs to perform operations like booking, querying, and calculation.
- Multi-agent systems: Multiple agents with distinct roles collaborate—for example, one plans, one executes, and one validates—to complete complex projects together.
1.3 Typical Application Scenarios
Agents are widely used in intelligent customer service, enterprise knowledge base Q&A, office automation, coding assistance, data analysis, and content creation. In enterprise scenarios, developers often obtain model inference capabilities from cloud-based LLM services (for example, the Qianfan foundation model platform provided by Baidu AI Cloud) and then combine them with their own business data and tool interfaces to build agents tailored to their needs.
2. Technical Architecture of AI Agents
2.1 Core Modules
A complete agent typically consists of four core modules:
- Planning: Responsible for goal decomposition and path planning. Common strategies include Chain-of-Thought, task decomposition, and reflection mechanisms.
- Memory: Divided into short-term memory (session context) and long-term memory (vectorized historical experience), giving the agent context awareness across turns and sessions.
- Tools: External capabilities the agent can invoke, such as search engines, databases, calculators, and business APIs, usually injected into the model context as function descriptions (name, parameters, purpose).
- Action/Execution: Carries out tool calls or generates responses based on the plan, then parses the returned results to feed the next loop iteration.
2.2 Design Patterns
Mainstream agent design patterns include:
- ReAct: Interleaves reasoning and acting—the model first outputs its thought process, then decides which tool to call.
- Plan-and-Execute: Generates a complete plan upfront and then executes it step by step; well suited for long tasks with clearly defined steps.
- Reflection: Self-evaluates execution results and automatically corrects deviations, improving task success rates.
2.3 Inference Engine and External Interaction
The agent’s inference engine is the underlying LLM. When selecting a model, you should weigh reasoning capability, context length, function-calling support, and usage cost. Developers can access inference capabilities through cloud APIs (such as the model services on Baidu AI Cloud’s Qianfan platform) or through locally deployed open-source models. The standard way to interact with external systems is HTTP-based API calls and structured function-calling protocols: the model outputs a JSON-formatted call instruction, which the host program parses and executes.
2.4 Agent Workflow
A typical workflow looks like this: receive the goal → assemble context (system prompt + memory + tool descriptions) → model inference → decide whether a tool call is needed → execute the tool and return the result → loop until a final answer is produced. In engineering practice, you should also add a maximum loop count, timeout controls, and exception fallbacks to prevent infinite loops and wasted resources.
3. Setting Up the Development Environment
3.1 Choosing a Development Path
There are two main approaches. The first is using an online low-code agent platform to quickly build applications through visual orchestration—ideal for prototyping. The second is local, code-based development, which gives you full control over prompts, tool orchestration, and data processing—better suited for production-grade applications. A local setup typically requires: a Python runtime, a package manager, an LLM API key, and optionally a vector database and a workflow orchestration framework.
3.2 Hands-On: A Minimal Agent Call Example
Below is a function-calling example based on a generic LLM API (pseudocode style, adaptable to any compatible interface):
import jsonfrom http.client import HTTPSConnection# 1. Define the tool descriptiontools = [{"type": "function","function": {"name": "get_weather","description": "Query the weather for a specified city","parameters": {"type": "object","properties": {"city": {"type": "string"}},"required": ["city"]}}}]# 2. Send the request; the model decides whether to call a toolmessages = [{"role": "user", "content": "What's the weather like in Beijing today?"}]response = call_llm_api(messages=messages, tools=tools)# 3. Parse the tool call instruction and execute itif response.get("tool_calls"):call = response["tool_calls"][0]args = json.loads(call["function"]["arguments"])result = get_weather(**args) # Execute the real business functionmessages.append({"role": "tool", "content": str(result)})final = call_llm_api(messages=messages) # The model summarizes the resultprint(final["content"])
This flow illustrates the agent’s basic closed loop: the model understands the intent, outputs a structured call instruction, the host program executes it, and the result is returned to the model to generate the final answer.
4. Prompt Engineering in Practice
4.1 Characteristics and Roles of Prompt Engineering
Prompt engineering is the technique of carefully designing input text to guide the model toward high-quality outputs. There are three main roles in a prompt: system (defines the agent’s identity, capability boundaries, and behavioral rules), user (the user’s input), and assistant (the model’s previous replies, which can be used for few-shot examples). In agent scenarios, the system prompt should also inject the tool list, output format constraints, and safety boundaries.
4.2 Common Prompt Frameworks
The industry has developed several structured prompt frameworks to help developers write prompts systematically:
- ICIO: Instruction, Context, Input, Output—suited for well-defined tasks.
- CRISPE: Capacity and Role, Insight, Statement, Personality, Experiment—emphasizes role shaping.
- BROKE: Background, Role, Objectives, Key Results, Evolve—suitable for complex prompts that require continuous refinement.
- CO-STAR: Context, Objective, Style, Tone, Audience, Response—commonly used for content generation tasks.
Using ICIO as an example, a system prompt for a weather assistant could read: “You are a weather assistant (role/instruction); users come from major cities (context); users will ask about the weather in a specific city (input); call the weather tool to retrieve data and answer concisely, including temperature and suggestions (output requirements).”
4.3 Prompt Optimization Tips
In practice, follow these principles: give specific and explicit instructions, provide few-shot examples, define the output format clearly (e.g., a JSON Schema), set refusal and fallback rules, and iterate continuously through A/B testing. For agents, you should also write tool-usage rules and exception-handling strategies explicitly into the system prompt—this significantly reduces erroneous tool calls.
5. Conclusion and Outlook
This article has walked through the complete path of AI agent development, from concepts and architecture to environment setup and prompt engineering. By mastering the three core mechanisms—planning, memory, and tool calling—combined with structured prompt design, developers can use cloud-based LLM services (such as Baidu AI Cloud’s Qianfan platform) or local inference environments to build agents ranging from simple Q&A bots to complex task automation systems. As model reasoning capabilities grow stronger and multi-agent collaboration frameworks mature, agents will play an increasingly central role in enterprise digital workflows. Start with a small scenario, get hands-on, and iterate continuously.
