What Are AI Agents and Agentic AI?
AI agents are software systems that pursue a goal by selecting actions, using tools, and deciding what to do next based on the results. In an LLM-based agent, a language model proposes actions and a runtime controls what actually happens. Agentic AI describes this goal-directed pattern, including systems that adapt across several steps within limits set by the application.
A typical chatbot receives a question and returns text. An agent can receive a goal such as “Find a Dubai itinerary that fits my budget,” query flight and hotel services, and change its search when a suitable flight arrives too late for the current hotel option. Both systems can use the same large language model. The difference is in the application: does it use observations to select and execute further actions?
| System | Who selects the next step? | Travel example |
|---|---|---|
| Chatbot | The user provides the next request. | Suggests places to visit from information already in context. |
| Fixed workflow | Application code follows predefined steps and branches. | Always searches flights, then hotels, then renders a template. |
| LLM-based agent | The model proposes a step based on the goal and observations, subject to runtime policy. | Changes the hotel area after seeing prices and checks how the change affects travel time. |
The boundary is a design choice. A single model-selected weather lookup demonstrates tool use, with little need for planning. A multi-step agent has more discretion over what to do next, but its authority should still be narrow. For example, it may choose which hotels to search without being allowed to book any of them. If the task has a predictable sequence, start with a fixed workflow and introduce model-selected steps only where they solve a specific problem.
How Do AI Agents Use LLMs, Tools, and Memory?
The LLM interprets the goal, proposes a tool call or an answer, and interprets observations. The tools supply capabilities such as searching an API, reading a database, running a calculation, or updating a record. Memory holds information the application may need later. A separate runtime connects them: it builds the model input, validates proposed actions, calls tools, records outcomes, and decides when the loop must stop.

At each step, the application computes a model input from some combination of instructions, the user goal, tool schemas, selected memory, and recent observations. The model responds with text, tool requests, or both. Selecting a tool is therefore a decision based on the information in that input. If the runtime omits the user's dates or includes a stale search result without its timestamp, the model may choose an action that fits the visible context and still fails the real task.
- Working state: Structured data for the current run, such as dates, budget, candidate IDs, completed steps, and remaining call allowance. Store hard constraints as fields that code can check.
- Conversation history: Recent user messages and tool results, or a summary of earlier turns. Summaries save space but can lose conditions such as “arrive before 6 pm.” Keep those conditions separately.
- Persistent memory: Data retained across sessions, such as a preferred departure airport. Store it with a user identifier and define how it can be corrected or deleted.
Memory does not automatically change model weights. The application selects what to load into the model's context window on each call. It can fetch exact settings from a database and use retrieval-augmented generation for relevant documents. Keep their roles distinct: a stored preference for Cochin International Airport can supply a default, but “depart from Trivandrum this time” is an explicit constraint for the current run. A retrieved document is evidence to inspect, not a source of permission to act.
What Is Function Calling in AI Agents?
Function calling, also called tool calling, is an interface for representing proposed actions as structured data. The application sends tool names, descriptions, and argument schemas to the model. For “What's the weather in Trivandrum?”, the model might propose the function get_weather with arguments {"location":"Trivandrum"}. The application maps the name to a registered handler. A model response containing that request does not invoke the Python function on its own.
- Advertise tools: Describe what each function does, what arguments it accepts, and when the model should use it. Expose only tools relevant to the current task.
- Read the request: Extract the tool name, call ID, and arguments. In the Chat Completions example below, the arguments arrive as a JSON string and must be parsed.
- Validate and authorise: Check the name against an allowlist, validate argument values, and enforce permissions. A valid record ID does not establish that the current user may read that record.
- Execute and return the observation: Run the registered function, then send its result back with the original call ID. The ID lets the API associate a result with the corresponding request.
- Continue or stop: Let the model interpret the result. The runtime can allow another call, return a final answer, or exit with a controlled error.
A schema can require a location string and reject unexpected fields. It cannot prove that a service will return fresh weather or that the requested location matches the user's intent. Return data with explicit units, freshness, source, and status where those fields matter. For instance, a timeout should appear as a failed lookup, never as a successful response whose missing temperature gets filled in by the model.
Worked Example: Python Function Calling for a Weather Agent
This example uses the OpenAI Python SDK and the Chat Completions interface. Set OPENAI_API_KEY and set OPENAI_MODEL to a model available to your account that supports strict function calling. The weather handler returns a fixture, so the script makes model API requests but no weather API request. The first model call requires a tool request; the second receives the observation and has no tools available.
import json
import os
from openai import OpenAI
client = OpenAI(timeout=20, max_retries=0)
model = os.environ["OPENAI_MODEL"]
def get_weather(location):
return {
"location": location,
"temperature_c": 29,
"condition": "cloudy",
"source": "demo fixture",
"is_live": False,
}
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Read a simulated weather record for Trivandrum.",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "enum": ["Trivandrum"]}
},
"required": ["location"],
"additionalProperties": False,
},
},
}]
messages = [
{
"role": "system",
"content": (
"Report only the weather fields returned by the tool. "
"If is_live is false, state that the data is simulated."
),
},
{"role": "user", "content": "What's the weather in Trivandrum?"},
]
proposal = client.chat.completions.create(
model=model,
messages=messages,
tools=tools,
tool_choice="required",
parallel_tool_calls=False,
).choices[0].message
calls = proposal.tool_calls or []
if len(calls) != 1 or calls[0].function.name != "get_weather":
raise RuntimeError("Expected one allowed weather call")
call = calls[0]
try:
args = json.loads(call.function.arguments)
except json.JSONDecodeError as exc:
raise RuntimeError("Tool arguments were not valid JSON") from exc
if args != {"location": "Trivandrum"}:
raise RuntimeError("Invalid weather arguments")
result = get_weather(**args)
messages.append({
"role": "assistant",
"content": proposal.content,
"tool_calls": [call.model_dump(exclude_none=True)],
})
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
answer = client.chat.completions.create(
model=model,
messages=messages,
).choices[0].message
if not answer.content:
raise RuntimeError("No final weather answer")
print(answer.content)
Trace the run: the model proposes one call with {"location":"Trivandrum"}, the runtime checks the exact name and arguments, and Python returns temperature_c=29 and is_live=False. An acceptable answer is “The simulated weather for Trivandrum is 29°C and cloudy. This is not a live reading.” The program executes at most one tool call. If the simulation disclosure must always appear, render it directly from is_live in application code; the model instruction alone does not enforce it.
Test the dispatcher separately from the model. Supply a valid call, malformed JSON, an unexpected function name, and a different location. Only the valid case should reach the handler. For a live integration, add tests for a timeout, absent temperature, and a timestamp older than your freshness limit. Verify that the application reports unavailable data instead of forwarding an incomplete record as if the lookup succeeded.
How Do AI Agents Plan, Execute, and Replan?
Planning identifies steps and dependencies. A Dubai travel assistant needs the departure city, dates, number of travellers, and budget before it can compare options reliably. It can search flight options first, then use arrival and departure times to determine hotel dates and check-in constraints. Searches for attractions can run independently once the destination is known. If a required field is missing, asking a focused question is often better than running several speculative searches.

- Goal: Plan a three-night Dubai trip for one person with a total budget of ₹55,000. Return options without booking.
- Plan and call: Use
search_flightsandsearch_hotelsfor the requested dates. Compare prices in the same currency, for the same number of travellers, and with known fees included. - Observe: In this example, the flight costs ₹29,000 and the first hotel costs ₹8,000 per night. The subtotal is
29000 + 3 * 8000 = 53000, leaving ₹2,000. - Replan: The user wants at least ₹5,000 available for food and local transport. For the selected flight, the hotel cap per night is
(55000 - 29000 - 5000) / 3 = 7000. Search again with that cap and check whether the new hotel location makes local transport more expensive. - Stop and respond: A hotel at ₹6,500 per night gives a subtotal of ₹48,500 and leaves ₹6,500. Use
search_placesto check opening hours for the proposed itinerary. List any unverified charges separately and state that nothing was booked.
The observation changes the next action: the first subtotal fits the headline budget but violates the spending reserve. Code can check both constraints without asking the model to do the arithmetic. Keep the plan as a small, revisable list of pending and completed steps. Save observations with the candidate IDs and search parameters that produced them so the agent does not combine a hotel quote from one date range with a flight from another.
Define stop rules before starting the loop. Stop when all mandatory checks pass, when progress requires a user decision, or when the run hits a call or time limit. A repeated search with identical arguments and no change in state is a useful sign that the loop has stalled. Return verified partial results and say which checks remain. A booking, if offered at all, should be a separate operation that requires approval for the specific itinerary and quoted price.
Where Are AI Agents Used in Real Applications?
Choose tasks where the next step depends on what a tool returns. Also pick a measurable outcome: a support agent should retrieve the correct order status, while a research agent should preserve sources for factual claims. A polished final answer can hide failures in both cases.
| Application | Tool-driven work | Control to build first |
|---|---|---|
| Personal assistant | Search itineraries, draft email, or find free calendar slots. | Keep drafting separate from sending or event creation. |
| Customer support | Read current order data and retrieve the relevant policy. | Scope lookups to the authenticated customer. |
| Research | Search, compare sources, and build a cited report. | Store source IDs and distinguish claims from interpretation. |
| Data analysis | Query a dataset, calculate grouped metrics, and generate charts. | Use read-only access and check units, filters, and row counts. |
| Coding | Edit a patch and run tests to check it. | Run tests in an isolated workspace without production credentials. |
| Multimodal processing | Extract invoice fields or locate moments in a recording. | Keep page or timestamp references for review. |
| Enterprise operations | Route finance, HR, or operations requests using policy and records. | Use role-based access and approval for sensitive changes. |
With multimodal AI, observations can contain images, audio, or video rather than only text. An invoice agent may read a scanned total, cross-check it against line items, and ask for review if they disagree. The source region matters: a reviewer should be able to inspect the exact page and field instead of trusting a transcription with no trace back to the document.
Why Do AI Agents Fail, and How Do You Evaluate Them?
Failures can start in the model, the tool, or the runtime. A model can select the wrong tool or invent a confirmation. A tool can return stale data, time out, or change its response format. The runtime can lose state or repeat a write. Longer tasks allow more errors to carry forward: if four mandatory steps each have an independent 0.95 chance of succeeding, the chance that all four succeed is 0.95 ** 4 = 0.8145 approximately. That is an illustration, not a benchmark; actual errors may be correlated, and recovery can change the outcome.
- Incorrect or unsupported results: Compare key claims against recorded tool observations. A statement such as “the reservation is confirmed” needs a recorded successful response, not an inference from a pending request.
- Tool outages and repeated writes: Use timeouts and bounded retries. For a write with an uncertain outcome, check its status before repeating it, and use an idempotency key where the service supports one.
- Untrusted content and permissions: Retrieved pages, emails, and tool results can contain instructions. Treat them as data. Enforce access rules and approval in the runtime, even if the model requests a valid tool call.
- Cost and latency: A dependent sequence waits for each model call and tool request in turn. Run independent reads concurrently where practical, and track model tokens, elapsed time, and tool requests per completed task.
Build a test set containing ordinary goals, ambiguous inputs, unavailable services, and actions the user is not allowed to perform. Record the tool name, redacted arguments, outcome, elapsed time, and stop reason. Evaluate goal completion, constraint violations, evidence support, and unnecessary calls separately. For instance, a travel run that returns a valid itinerary after six searches can pass on correctness and still miss a three-call budget. See the chapter on LLM hallucination, evaluation, and safety for ways to test the final answer alongside the action trace.
Key Takeaways
- AI agents use observations to decide what action to propose next; the runtime controls actual execution.
- Function calling communicates structured requests. Validate names, arguments, and user permissions before dispatch.
- Keep hard constraints in structured state. Load relevant memory into context without treating it as current instruction or authority.
- Use deterministic code for arithmetic, schema checks, and operations that require exact outcomes.
- Bound the agent loop with explicit success criteria, call limits, and stop reasons.
- Evaluate final answers and tool traces separately, including what happens when a dependency fails.
Frequently Asked Questions
What is the difference between AI agents and agentic AI?
An AI agent is a concrete system that selects actions towards a goal and observes the results. Agentic AI is a broader description of this design pattern. It can describe one agent, several coordinated components, or a mostly fixed application with bounded points where a model chooses what to do next.
Does every AI agent need long-term memory?
No. A weather lookup or a short data analysis task can use only the current request and recent results. Persistent memory is useful when users want preferences or unfinished tasks to carry across sessions. If you add it, define what may be stored, who can access it, and how stale information gets corrected.
Does function calling mean the LLM executes Python?
With application-defined functions, the model typically returns a structured request containing a function name and arguments. Your application parses and checks that request, invokes the registered handler, and sends the result back to the model. Some providers also offer hosted tools, in which case the provider handles execution under that tool interface.
Can RAG and AI agents work together?
Yes. An agent can use retrieval as a tool when it needs evidence, such as a policy clause or a product document. It may revise the query if the results are incomplete. If every request needs the same retrieval step and no further decisions, a fixed retrieval and generation pipeline is simpler to test.
How do you prevent an AI agent from taking unauthorised actions?
Give the runtime narrowly scoped credentials and enforce permissions for every tool call. Keep read operations separate from writes, and require approval for sensitive changes. Treat external content as untrusted data, even if it looks like an instruction. A prompt can guide model behaviour, but it cannot replace an access control check.