Function Calling, AI Agents, and RAG: Understanding the Underlying Logic of Agentic and Knowledge-Augmented Systems
This article explains how function calling, AI agents, retrieval-augmented generation (RAG), the Model Context Protocol (MCP), and skills mechanisms fit together in a real system. It clarifies a common misconception—that a model describing an action is the same as the model performing it—and shows how each mechanism solves a distinct problem across the understanding, execution, and data layers. Readers will learn the responsibility boundaries between models and applications, why structured calls are not automatic execution, how agents maintain task loops within limits, and how to build controllable, auditable intelligent applications through layered evaluation and independent protection for write operations.
1. Clarifying the Problem First: Models Generate Text, Systems Execute Actions
When discussing agent-related technology, the most common misconception is treating “the model can describe an operation” as “the model has already performed the operation.”
For example, a user might say: “Check the delivery status of a specific order, and if it exceeds the promised time, create a support ticket.”
A language model can understand this request and generate both the query steps and the ticket content. But in a typical application architecture, the model itself does not have direct access to the order database, nor will it write a ticket based on a reply alone. The components that actually perform these actions are business programs outside the model.
Therefore, an intelligent application capable of completing a task needs at least three layers:
- Understanding and decision layer: identifies user intent, determines what information is missing, and selects the next action.
- Execution and control layer: validates call requests, checks permissions, executes tools, and maintains task state.
- Data and knowledge layer: provides business records, documents, rules, and execution results.
The language model typically handles part of the understanding and decision layer; the application handles execution and control; and databases, document stores, and business APIs provide the data and knowledge.
Function calling, retrieval-augmented generation, the Model Context Protocol, and skills mechanisms are the technical means that solve different problems across these layers. They are not interchangeable features of the same kind, but distinct capabilities that can be combined.
2. Function Calling: Turning Language Intent into a Processable Call Request
1. Why Natural Language Cannot Be Parsed Directly
Suppose the model replies:
“Please check the delivery status for order number 123456 and return the latest logistics update.”
A human can understand this sentence, but a program still needs to determine:
- Which business function should be called?
- Is the order number a string?
- Are historical logistics records required?
- When a parameter is missing, should a default value be used, or should the user be asked to supply it?
- Is this sentence requesting execution, or merely quoting an example?
If you rely on keyword matching or text extraction, a change in wording can cause errors. More seriously, explanatory content generated by the model may be mistaken for an execution instruction.
Function calling reduces the ambiguity of natural-language expression by predefining tool names, parameter structures, and required constraints, so the model produces a call request that is easier for a program to parse.
2. It Is an Interaction Convention, Not an Automatic Execution Capability
The core of function calling is a structured interaction mechanism between the model and the application.
The application tells the model which tools are available and their parameters; the model generates a tool call request based on context; the application parses the request and decides whether to execute it; and the execution result is returned to the model for subsequent answering or further decisions.
Three concepts must be distinguished:
- Generating a call request: the model proposes which tool to call.
- Permitting the request: the application confirms the request satisfies permissions and business rules.
- Actually completing the operation: the business system executes it and returns the real result.
So “the model called the tool” usually means, in engineering terms, that the model proposed a call request and an external program performed the actual call. Tool names and parameter formats help the system recognize an action, but they cannot replace security controls on the execution side.
3. A Structured Call Example
The following is an illustrative message structure defined here for demonstration; it is not a fixed interface of any particular service:
{"action": "query_order_status","arguments": {"order_id": "123456"}}
This content only expresses: “I want to run an order status query with the specified order number.”
The application still needs to check:
- Whether
actionbelongs to the set of tools allowed to be called. - Whether
argumentsconforms to the parameter structure. - Whether the type, length, and format of
order_idare valid. - Whether the current user is authorized to access the order.
- Whether the query is within rate limits, timeouts, or other runtime constraints.
Only after these checks pass can execution proceed.
Structured output improves machine parseability; it does not inherently guarantee business correctness. A valid structure can still contain a wrong order number, an unauthorized target, or an action that violates business conditions.
3. AI Agents: Organizing a Task Loop on Top of the Calling Mechanism
Function calling solves “how to express a single tool call.” An AI agent goes further and solves “how to keep advancing a task.”
A typical agent run can be summarized as:
Receive goal → gather context → decide the next step → propose an action → execute and observe the result → continue or finish.
For example, in an order-handling scenario:
- Identify that the user wants to check delivery status.
- Check whether the order number has been provided.
- If information is missing, ask the user for it.
- Call the query tool to retrieve the order record.
- Determine whether there is an exception based on the promised time and actual delivery status.
- If a ticket needs to be created, check authorization and confirmation requirements.
- Perform the creation action and report the real result to the user.
Throughout this process, the model does not simply generate an answer; it participates in multiple decision steps. The application maintains state and ensures every action stays within a controllable range.
1. An Agent Is Not an Infinite Loop
If a system lets the model keep trying tool calls, it may produce repeated queries, ineffective retries, or even repeated execution of operations with side effects.
Real applications should set clear runtime boundaries:
- Maximum number of execution steps.
- Timeout for a single tool call.
- Overall task time budget.
- Retry count and retry conditions.
- Termination rules when no progress is made.
- Human-in-the-loop confirmation points for high-risk operations.
The model can suggest the next step, but termination conditions, permission rules, and resource budgets should be enforced reliably by the application.
2. Fixed Workflows and Agents Are Not Opposites
When the business path is stable and the rules are clear, a fixed workflow is often easier to test and audit. Model-based decisions are only necessary at points where the path is uncertain and dynamic judgment is required.
For example, querying an order can be handled by a deterministic process; interpreting a user’s vague request and deciding what information to gather can be delegated to the model.
A more practical design is often: deterministic programs manage the main flow, while the model handles uncertainty within a limited scope. This provides flexibility while keeping system complexity under control.
4. Retrieval-Augmented Generation: Solving the Problem of Insufficient Basis for Answers
Retrieval-augmented generation, usually abbreviated as RAG, works by first retrieving content relevant to a question from an external knowledge source, then passing that content to the model to help generate an answer.
It mainly solves two kinds of problems:
- The model did not cover certain internal materials during training.
- Business knowledge keeps changing and cannot rely solely on what the model already knows.
For example, if a user asks about the latest after-sales handling rules, the application can retrieve the relevant policy clauses from the knowledge base and have the model explain the applicable conditions based on those clauses, rather than answering from the model’s memory alone.
1. Retrieval Is Not Simply Concatenating Documents
A complete retrieval-augmented pipeline typically includes:
- Document collection and cleaning.
- Splitting text according to content structure.
- Building a searchable index.
- Understanding the user query and retrieving candidate content.
- Filtering materials by relevance, permission, and freshness.
- Providing the necessary snippets to the model.
- Generating a grounded answer while preserving source information.
Retrieval can use keyword matching, semantic retrieval, or a combined strategy. The specific choice depends on the characteristics of the data, and one retrieval method should not be equated with the entire RAG approach.
2. The Relationship Between RAG and Function Calling
Retrieval-augmented generation is a way of acquiring knowledge and organizing answers; function calling is a structured calling mechanism.
An application can run retrieval as a fixed step before calling the model, or it can package retrieval as a tool that the model requests when needed.
Therefore:
- Using RAG does not necessarily mean using an agent.
- Using function calling does not necessarily involve knowledge retrieval.
- An agent can treat retrieval as one step in advancing a task.
Document knowledge should also be distinguished from real-time business state. Policy descriptions can come from a knowledge base, but information such as an order’s current status, account balance, and inventory count usually needs to be queried from authoritative business data sources and cannot simply be replaced by historical documents.
3. Retrieved Results May Also Be Untrustworthy
Retrieved content may be outdated, mutually contradictory, or even contain text that tries to induce the system to perform extra actions.
The application should treat document content as data to be referenced, not as new system instructions. Statements like “ignore the previous rules” appearing in a document should not change tool permissions or execution policies.
At the same time, knowledge retrieval must respect access control. Documents a user is not authorized to view should not be provided to the model just because they entered the retrieval path.
5. Model Context Protocol: Making Resource Access More Consistent
The Model Context Protocol, usually abbreviated as MCP, focuses on standardized connections between an application and external capabilities such as tools and resources.
If integrating each external system requires redesigning tool discovery, parameter description, result passing, and communication handling, maintenance costs rise quickly. The value of a unified protocol is to make these connection methods more consistent and reduce repeated adaptation.
1. It Sits at a Different Place Than Function Calling
Two questions help clarify the difference:
- Function calling: how does the model express to the application “I want to run this tool”?
- Model Context Protocol: how does the application connect to external capabilities under a unified convention and obtain their descriptions or call results?
The two can work together. The application connects to tools through the protocol and provides appropriate tool descriptions to the model; after the model generates a call request, the application routes the request to the corresponding tool.
However, not every system must adopt a standardized connection protocol. When there are few tools and the interfaces are stable, adapting directly to business APIs may be simpler. Whether a protocol is worth introducing should be judged by integration scale, reuse needs, and maintenance cost.
2. Unified Connections Do Not Remove Trust Boundaries
A tool being discoverable does not mean it can be called arbitrarily.
After connecting to external capabilities, you still need to check:
- Whether the tool provider is trustworthy.
- Whether the tool description is accurate.
- Whether the request carries sensitive information.
- Whether the returned results need to be masked.
- Whether the current identity can perform the operation.
- Whether the call produces side effects such as writes, deletions, or outbound sending.
Standardized protocols mainly reduce connection complexity; they cannot automatically solve business authorization, data security, or result authenticity problems.
6. Skills Mechanism: Turning Experience into Reusable Task Methods
The term “skill” does not have a fully unified definition across all systems. In general, it can be understood as a reusable capability package organized around a certain class of task, possibly containing operating instructions, step templates, reference material, examples, and helper scripts.
For example, a “business report analysis” skill might specify:
- First confirm the statistical period and metric definitions.
- Check for missing data and outliers.
- Distinguish facts, inferences, and recommendations.
- Output the analysis in a consistent structure.
- Clearly mark uncertainty for judgments that lack evidence.
A skill mainly answers “how should this kind of task be done,” while a tool mainly answers “what actions can the system perform.”
A skill can guide the model in choosing tools, but it cannot grant access permissions on its own; nor can it guarantee that every execution is correct. Skill content needs version management, evaluation, and maintenance—especially when it involves business rules, the applicable scope and update responsibility should be made explicit.
7. Putting the Different Mechanisms into One Business Chain
Taking “handle delivery exceptions according to current policy” as an example, the mechanisms can collaborate like this:
- The agent maintains task state and determines what information is currently missing.
- The skill provides the method and output requirements for handling exceptions.
- RAG retrieves the current handling policy and applicable clauses.
- Function calling expresses order query or ticket creation requests.
- The Model Context Protocol, in architectures that adopt it, provides a consistent way to connect tools.
- The application performs parameter validation, authorization, confirmation, calls, and auditing.
- The model generates the final explanation based on real query results and policy references.
This chain shows that what determines system reliability is not whether every term is present, but whether each layer fulfills its correct responsibility.
Knowledge retrieval should not impersonate a real-time query; skill instructions should not bypass permissions; actions proposed by the model should not be executed without checks; and a tool failure should not be dressed up as a successful result.
8. Engineering Practice: Ensure Controllability First, Then Pursue Autonomy
1. Start with the Smallest Closed Loop
Prioritize tasks with clear boundaries and verifiable results, such as querying status, explaining rules, or generating drafts. First connect a small number of read-only tools, verify call selection, parameter accuracy, and result feedback, then gradually add write operations.
More tools do not necessarily mean better results. Overlapping tool responsibilities, vague naming, or overly long descriptions can all increase the probability of the model choosing the wrong tool.
2. Establish Independent Protection for Write Operations
Operations such as creating tickets, modifying records, and sending notifications should have stricter execution rules.
Common measures include:
- User confirmation or business approval.
- Least-privilege authorization.
- Idempotency control to avoid repeated execution.
- Re-checking business state before execution.
- Saving operation records to support auditing and tracing.
In particular, after a write operation times out, you cannot directly assume it failed and call it again, because the request may already have taken effect on the business side. You should first query the execution status, or rely on an idempotency mechanism to handle duplicate requests.
3. Make Errors Identifiable and Recoverable
Tool results should distinguish success, parameter errors, insufficient permissions, missing resources, and temporary unavailability.
Different errors require different strategies:
- Parameter error: supply or correct the parameters.
- Insufficient permissions: stop the related operation and do not attempt to bypass the restriction.
- Temporary unavailability: retry a limited number of times within budget.
- Resource not found: verify the input or inform the user.
- Incomplete result: continue querying or clearly state the information gap.
The model can help explain errors, but the error type and execution state should be provided by the program, not guessed by the model.
4. Evaluate in Layers, Not Just Whether the Answer Is Fluent
When evaluating an intelligent application, check separately:
- Whether it understood the user’s real goal.
- Whether it chose the appropriate tool.
- Whether the parameters were correct and complete.
- Whether the retrieval results were relevant, up to date, and accessible.
- Whether it followed confirmation and authorization requirements.
- Whether the final statement was consistent with the real execution result.
- Whether it finished the task within a reasonable number of steps.
The test set should also cover missing information, conflicting rules, repeated requests, tool timeouts, and privilege-escalation inducement. Passing the normal path only shows the system has basic capability; it does not prove the system is ready for production.
9. Summary: Understand Technology Through Responsibility Boundaries, Not by Piling Up Concepts
Function calling makes the actions a model proposes easier for a program to recognize; the agent organizes continuous decisions and task advancement; retrieval-augmented generation supplements the basis for answers; the Model Context Protocol standardizes external capability connections; and the skills mechanism captures reusable task methods.
Together they serve one goal: connecting the language model from “generating text that looks reasonable” to “a business process that can be verified, executed, and traced.”
A truly reliable system needs to manage data sources, tool permissions, execution state, and task boundaries at the same time. Letting the model handle the understanding and judgment that suit it, and letting the program take on the rules that must execute deterministically, is the more robust underlying logic for building intelligent applications.
