Skip to content
ImagineWorld

The Need for Tools and External Integrations

node_idnode-book_ai-agents-in-practice_chapter-05-the-need-for-tools-and-external-integrations
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleThe Need for Tools and External Integrations
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 5 — The Need for Tools and External Integrations

Section titled “Chapter 5 — The Need for Tools and External Integrations”

As we mentioned in the preceding chapters, one of the key features and differentiations of AI agents is that they can interact with the world. While LLMs can understand, reason, and generate text, they are ultimately limited by what exists within their training data and current context window. To go beyond passive conversation and perform real, useful actions—such as booking appointments, querying databases, retrieving live information, or executing multi-step workflows—AI agents must be equipped with tools.

Tools are the functional extensions of an agent’s intelligence. They allow agents to call APIs, access external systems, retrieve fresh data, and even manipulate structured knowledge bases.

Throughout this chapter, we will cover the following topics:

  • The anatomy of an AI agent’s tools
  • Hardcoded and semantic functions
  • APIs and web services
  • Databases and knowledge bases
  • Synchronous versus asynchronous calls

By the end of this chapter, you’ll understand how tools transform LLMs into capable agents—and how to design, connect, and manage those tools to build intelligent, action-oriented systems.

You can access the complete code for this chapter in the book’s accompanying GitHub repository at https://github.com/PacktPublishing/AI-Agents-in-Practice.

Tools can be defined as an AI agent’s capabilities of “doing things.” Those things can range from scraping the web to sending an email, from getting your calendar’s appointments to executing an action against a website. As we will see in the upcoming sections, tools can effectively empower agents in numerous ways depending on the way their core logic is designed. Nevertheless, tools share a common anatomy that we can keep in mind while designing our agentic application.

However, before jumping straight into the anatomy of a tool, we first need to gain some clarity on the terminology.

As mentioned in Chapter 2, when talking about AI agents, you will often hear the terms tasks, tools, skills, plugins, functions, and actions as interchangeable ways to refer to an agent’s capabilities of “doing things.” You will also see that different AI orchestrators come with different terminology. For example, Semantic Kernel leverages the term plugin, which in turn is made of one or more functions. On the other hand, LangChain uses the term tool.

Although we could differentiate these terms semantically (plugins as integrations, functions as operations, skills as proficiencies…), they generally refer to the same concept: an AI system acting on behalf of the user. For consistency, we will use the term tool throughout this book.

So, back to the anatomy of a tool: what are the main ingredients of an AI agent’s tool?

At a high level, a tool is defined by the following components:

  • A name, which is the unique identifier of the tool. For example, a tool that can schedule an appointment in our calendar could be called “CalendarTool.”
  • A description, which defines the tool’s capabilities. As mentioned throughout this book, this element is key. In fact, it will be the label that our AI agent’s brain—the LLM—will read to understand whether to invoke it (depending on the user’s query) and, if so, with which parameters. For example, the CalendarTool could have a description such as the following: This tool is integrated with the user’s calendar and is able to read existing meetings, schedule new meetings, and recall meetings and any other activities related to calendar management.
  • Core logic, which is the proper engine of the tool. For example, CalendarTool will have different methods (getting existing meetings, creating new meetings, etc.) that can be defined as Python functions. In the following code example, we are leveraging Outlook as a calendar, meaning that we will need to connect to Microsoft Graph:
    def get_outlook_calendar_events(
    access_token: str, date: str = None
    ):
    """
    Fetches Outlook calendar events for a given date using Microsoft Graph API.
    """
    if not date:
    date = datetime.today().date().isoformat()
    start_datetime = f"{date}T00:00:00"
    end_datetime = f"{date}T23:59:59"
    url = (
    "https://graph.microsoft.com/v1.0/me/calendarview?"
    f"startDateTime={start_datetime}&endDateTime={end_datetime}"
    )
    headers = {
    "Authorization": f"Bearer {access_token}",
    "Content-Type": "application/json"
    }
    response = requests.get(
    url,
    headers=headers
    )

(1) to quickly copy code into your coding environment, or click the Explain button

(2) to get the AI assistant to explain a block of code to you.

Now, in the preceding example, the core logic of the tool is based on an API integration—in fact, we are executing an operation with the Microsoft Graph APIs. However, when we talk about AI tools, the core logic behind them can vary depending on the use case and integration needs.

In the next sections, we are going to examine some of them.

This category refers to logic that is explicitly defined by the developer, either through traditional programming constructs (hardcoded logic) or using natural language descriptions (semantic functions).

Hardcoded functions are traditional pieces of logic implemented in code. They are deterministic and task-specific, meaning they do exactly what the developer tells them to do. These functions are ideal for simple utilities, calculations, formatting, or business rules that don’t require external APIs or learning.

For example, we could have a tool to convert the temperature from Celsius to Fahrenheit:

def convert_celsius_to_fahrenheit(celsius: float) -> float:
return (celsius * 9/5) + 32

We can wrap this function as a tool for our AI agent by adding two additional ingredients: name and description. Among the various methods we have to do that, we can leverage LangChain’s tool decorator, which will automatically infer the name and description as follows (we will extensively cover LangChain’s components and taxonomy in Chapter 6):

@tool
def convert_celsius_to_fahrenheit(celsius: float) -> float:
"""tool to convert temperature from celsius to Fahrenheit"""
return (celsius * 9/5) + 32

The tool will use the name of the function as its name (convert_celsis_to_fahrenheit) and the docstring as its description. An AI agent could invoke it when asked, for example, “What’s 20 degrees Celsius in Fahrenheit?”

These types of hardcoded functions are fast, lightweight, and require no external dependency, making them ideal for utility logic.

Semantic functions, on the other hand, are described in natural language but mapped to code under the hood. They are especially powerful in frameworks such as Semantic Kernel: in this framework, the taxonomy is that of plugins as a set of functions. When it comes to semantic plugins, the typical structure is as follows.

Let’s consider an example of one of the built-in plugins available in the Semantic Kernel framework, WriterPlugin:

WriterPlugin/
└── Acronym/
├── config.json
└── skprompt.txt
└── AcronymGenerator/
├── config.json
└── skprompt.txt
└── Brainstorm/
├── config.json
└── skprompt.txt
….

This plugin comes with 16 functions. Each function is defined by a JSON file, where the function’s descriptions and other configuration parameters are set, and a text file, where the proper semantic skill is described in natural language.

Let’s examine, for example, the AcronymGenerator function’s anatomy:

  • Here’s the configuration file:
    {
    "schema": 1,
    "description": "Given a request to generate an acronym from a string, generate an acronym and provide the acronym explanation.",
    "execution_settings": {
    "default": {
    "max_tokens": 256,
    "temperature": 0.7,
    "top_p": 1.0,
    "presence_penalty": 0.0,
    "frequency_penalty": 0.0,
    "stop_sequences": [
    "#"
    ]
    }
    }
    }
  • Here’s the text file (truncated):
    # Name of a super artificial intelligence
    J.A.R.V.I.S. = Just A Really Very Intelligent System.
    # Name for a new young beautiful assistant
    F.R.I.D.A.Y. = Female Replacement Intelligent Digital Assistant Youth.
    # Mirror to check what's behind
    B.A.R.F. = Binary Augmented Retro-Framing.
    # Pair of powerful glasses created by a genius that is now dead
    E.D.I.T.H. = Even Dead I'm The Hero.
    # A company building and selling computers
    I.B.M. = Intelligent Business Machine.
    ….

As you can see, in the text file, there is no code whatsoever; it is nothing but a set of examples of acronyms so that an agent provided with this specific semantic function will be able to generate an acronym in a proper way and provide an explanation for it (as stated in the function’s description). Here’s an example:

  1. User input: “generate an acronym for a magic teletransportation helmet”
  2. AI agent output (powered by the acronym skill): “M.A.G.I.C. = Mobile Apparatus for Guaranteed Instantaneous Conveyance”

Typically, you might want to leverage hardcoded functions when you need precision, performance, or low-level logic. On the other hand, use semantic functions when you want to give the AI more flexibility to reason about whether a function is relevant based on natural language descriptions.

Now, when it comes to integrating your agent with external services, we need to introduce APIs and web services.

When extending the capabilities of an AI agent or tool, APIs and web services play a vital role in connecting language models to the outside world.

Definition

An Application Programming Interface (API) is a way for software applications to talk to each other. It defines a set of rules for how one program can request data or services from another—usually over the internet. APIs are everywhere: when your app gets the weather, loads your email, or books an Uber, it’s using an API.

APIs commonly follow the HTTP protocol and use methods such as the following:

  • GET: To retrieve data (e.g., getting the current weather for your city)
  • POST: To send new data (e.g., submitting a new user registration form)
  • PUT: To update existing data (e.g., editing your profile information)
  • DELETE: To remove data (e.g., deleting a saved address from your account)

These operations are part of what’s known as a RESTful API—a popular architectural style for building APIs on the web.

These tools act as connectors to live systems, enabling the AI to perform actions or retrieve real-time data from cloud platforms, third-party services, or enterprise backends. They essentially bridge the gap between the LLM’s reasoning and the real-time, dynamic digital environment it needs to operate in.

Note that, when we hear “API,” our minds often jump straight to web services such as Google Maps or OpenWeather, however, not all APIs are external—some live entirely within your application or enterprise environment. And that distinction matters a lot when you’re building tools for agents or orchestrating workflows with a language model.

Let’s explore the main types of APIs you’ll encounter.

Web APIs are exposed publicly (or semi-publicly) over the internet and often belong to third-party providers. They come with documentation, rate limits, and access tokens. These are the APIs you call when you want your AI to check the weather, send a message via Slack, or get stock prices from a financial service.

Note

A Web API is a remotely accessible service over HTTP or HTTPS, typically exposed via REST or GraphQL, that lets applications retrieve or manipulate data hosted elsewhere. Most SaaS platforms offer public-facing Web APIs.

Some examples include the OpenWeatherMap API (get weather by city), Stripe API (process payments), Microsoft Graph API (interact with Outlook, Teams, and OneDrive).

Many organizations have internal APIs running behind firewalls or inside virtual networks. These APIs power core business systems, such as inventory management, customer databases, booking engines, or HR platforms.

Note

Internal APIs usually require secure network access (such as a VPN or VNet integration).

Some examples of operations that you can run with internal APIs are as follows:

  • GET /orders/{id}: To fetch a customer’s order from your Enterprise Resource Planning (ERP) system
  • POST /leave-request: To create an employee leave request
  • GET /pricing-rules: To return internal pricing logic

If you’re building an AI agent for an enterprise, most of your tools will probably interface with internal APIs, not external ones.

Backend function APIs (service mesh or microservices)

Section titled “Backend function APIs (service mesh or microservices)”

In microservice-based architectures, different services expose internal HTTP APIs to communicate with each other. These are often containerized and may be deployed on Kubernetes, behind service meshes such as Istio or Linkerd.

Definition

Microservices are a software architecture style where an application is broken down into smaller, independently deployable services. Each service performs a specific business function and communicates with others through lightweight protocols such as HTTP APIs.

A service mesh is an infrastructure layer that manages communication between microservices in a secure, reliable, and observable way. It handles tasks such as traffic routing, load balancing, service discovery, authentication, and telemetry—without adding complexity to the microservices themselves.

From an AI’s point of view, these behave just like any other API—but with tighter latency and potentially no internet access required. They’re useful for internal orchestration when you’re building agents that handle multi-step logic across internal services.

Sometimes, the API you need doesn’t exist yet. With tools such as Azure Functions, AWS Lambda, or Google Cloud Functions, you can quickly create your own lightweight HTTP endpoints that act as dynamic tools.

Similar services leverage the serverless model, which flips the traditional idea of hosting: Instead of managing servers, scaling resources, or worrying about infrastructure, you just write your function, deploy it to a cloud provider, and it’s ready to be called via an API.

This approach is perfect for AI tool development because it allows you to spin up small, focused functions—each performing a single task, such as summarizing a document, formatting a report, or fetching filtered data from a system.

Once you understand the pattern, the possibilities are endless. Here are just a few examples of what API tools can do inside an agentic system:

ScenarioTool descriptionExample API
“Send a message to my team about the release.”Posts a real-time message to a shared communication platform such as Slack or Teams.Slack Web API: Use chat.postMessage to post updates to a specific channel.
“Create a new invoice in our internal finance system.”Pushes structured data (such as customer and amount) into a secure, internal accounting app.Internal Finance API: Use POST /invoices to create an invoice inside the company’s ERP system.
“Update the order status across internal services.”A microservice receives order status changes and updates other services accordingly.Order Service API: Use PATCH /orders/{id} to update order status across backend services.
“Extract keywords from a document for tagging.”A lightweight function receives raw text and returns extracted keywords for use in search or metadata.Azure Function: Use a custom POST /extract-keywords endpoint to return key terms from text input.

Table 5.1: Example of different APIs for different tasks

Understanding the distinction between web, internal, backend, and serverless APIs helps you design smarter, more modular, and more secure AI architectures.

As you build your tools, ask yourself the following:

  • Does the AI need to talk to the outside world? Web API.
  • Is the data locked behind your company firewall? Internal API.
  • Is this part of your app’s own backend logic? Microservice.
  • Need something fast and simple? Serverless function.

By choosing the right API type for the job, you set your AI agent up for success.

In the next section, we are going to explore another class of tools that are meant to add external knowledge to your agent.

As we explored in Chapter 1 of this book, adding external knowledge to LLMs was one of the first milestones achieved in the GenAI landscape, after the launch of ChatGPT. We saw how the typical pattern for grounding our LLMs on external knowledge is that of retrieval augmented generation (RAG). However, there are two main considerations to be made:

  • Data comes in a variety of formats, while RAG is typically suited for unstructured data (text, images, audio…)
  • When it comes to agentic AI, there are approaches to make traditional RAG pipelines more “intelligent,” thanks to the extra layer of reasoning, which is a feature of AI agents themselves

Henceforth, let’s start by distinguishing between the two main categories of data.

This is data that lives in rows, columns, and schemas—your classic SQL tables, CRM fields, and inventory records. It’s predictable, queryable, and easy to filter or sort. For this kind of data, tools often wrap the following:

  • SQL queries (SELECT * FROM orders WHERE status = 'pending')
  • API calls to business systems (e.g. Salesforce, SAP)

The second example—API calls to business systems—boils down to the category of tools we covered in the previous section (APIs and web services). Henceforth, we will focus on the scenario where we interact with structured databases through structured queries.

In the context of AI agents and, more broadly, AI applications, the typical consolidated pattern to enable smart database retrieval from natural language queries is the “text-to-query” approach. These are the high-level steps:

  1. The user asks a question in natural language—for example: “What is the most sold album in the US?”
  2. The LLM translates the query into a SQL statement – for example:
    SELECT album_name, artist_name, units_sold
    FROM album_sales
    WHERE country = 'US'
    ORDER BY units_sold DESC
    LIMIT 1;
  3. The LLM returns a well-written and conversational answer to the user from the query’s result – for example, the SQL query returns “The most sold album in the US is The Eagles’ Greatest Hits, with 38 million copies sold”.

This approach also holds for other kinds of structured data, whose query language might differ from T-SQL. From our AI agent perspective, it will boil down to the set of instructions that we set at the system message level and the tool description level.

This is the messy and information-rich kind of data: long-form text, emails, PDFs, audio transcripts, and chat logs. You can’t simply query it with a WHERE clause—you need semantic understanding.

In the context of LLMs, we explored how unstructured data is typically stored in vector databases and retrieved with RAG pipelines. However, as AI systems become more agentic, the role of retrieval must evolve. An agent is not just a passive model responding to input; it is an active decision-maker that evaluates the task, considers available tools, and determines how best to proceed. In this context, treating a vector database as a dynamic tool—rather than a fixed step—adds an important layer of reasoning. It allows the AI agent to decide whether retrieval is necessary, how to formulate an effective query, which source to target, and what to do with the information it receives.

This shift from static retrieval to agentic retrieval transforms RAG into a more deliberate, goal-oriented behavior.

Let’s consider the following example. We want to investigate the symptoms of long COVID and, to do that, we will rely on a set of clinical papers stored in a vector database. In a traditional RAG scenario, upon the user’s query “What are the symptoms of long COVID?”, this is a high-level view of what would happen:

  1. Input: The user submits the question as is.
  2. Embedding and retrieval: The system converts the question into a vector and performs a similarity search in the vector database of medical documents.
  3. Context injection: The top 3–5 matching documents are passed directly to the language model.
  4. Response generation: The model generates an answer based solely on the retrieved documents.

The output will likely be a reasonable summary of symptoms based on the most semantically similar passages—but without awareness of document type, source credibility, or context such as region, date, or patient type.

On the other hand, in an agentic RAG system, we might see something similar to the following:

  1. Understanding the intent: The agent parses the question and identifies that “long COVID” is a medical term, and the user is likely looking for a reliable clinical summary.
  2. Tool selection: It evaluates its available tools and determines that a vector search across peer-reviewed medical journals or official health guidance documents is most appropriate.
  3. Query refinement:The agent reformulates the query to
  4. “Current clinical symptoms and effects of post-acute sequelae of SARS-CoV-2 infection (PASC), known as long COVID.”
  5. Retrieval and reasoning: The vector database tool is invoked with this refined query. If results lack recent studies, the agent might retry with a date filter (e.g., post-2022) or switch to another knowledge source (e.g., CDC’s structured API).
  6. Multi-source synthesis: The agent extracts relevant information, filters out duplicates, and composes a response that distinguishes between common, rare, and emerging symptoms.

In this case, the outcome will be a grounded, context-aware answer tailored to the user’s needs, potentially including distinctions such as “in adults versus children” or noting the date of the latest findings.

Figure 5.1: Example of agentic RAG

Figure 5.1: Example of agentic RAG

This approach also enables more complex interactions as vector databases will ultimately be one of the many available tools for our agent. It means that the AI agent can combine retrieved data with other tools’ output or switch tools entirely if the vector database lacks the necessary domain coverage. In doing so, retrieval becomes not just a backend operation, but part of the agent’s broader decision-making loop.

Figure 5.2: Example of AI agent with multiple tools, including VectorDB as a tool

Figure 5.2: Example of AI agent with multiple tools, including VectorDB as a tool

Embedding vector databases as callable tools aligns retrieval with the principles of agent-based architecture: autonomy, adaptability, and contextual awareness. Rather than simply retrieving what is asked, the agent now determines what is worth retrieving—and why. This added layer of intelligence not only improves the accuracy and relevance of responses but also unlocks entirely new workflows in enterprise AI systems.

As we build increasingly intelligent AI agents—systems that reason, plan, and interact with external tools—it becomes essential to understand how these tools are called. One often overlooked, but critically important, distinction in agent tool design is whether a tool operates synchronously or asynchronously.

This isn’t just a technical implementation detail. The way a tool is executed affects the performance, scalability, and responsiveness of your agentic app.

First of all, let’s start by defining the concepts of synchronous and asynchronous calls in programming.

Figure 5.3: Example of synchronous and asynchronous process

Figure 5.3: Example of synchronous and asynchronous process

A synchronous call in programming is a function or method call that blocks further execution until it has completed. The program waits for the function to return a result before moving on to the next instruction. This pattern is straightforward and easy to reason about but can cause performance bottlenecks when dealing with slow operations such as file I/O, network requests, or database access.

For example, the following Python function reads a file synchronously:

# Synchronous file read in Python
with open("report.txt", "r") as file:
content = file.read()
print("File content loaded.")

In this case, the program will not print “File content loaded” until the entire file has been read.

An asynchronous call, on the other hand, is a non-blocking function invocation that allows the program to continue executing while the operation completes in the background. When the result is ready, it is handled through callbacks, events, or promises/futures, depending on the language. Asynchronous programming is essential for building responsive and scalable systems, especially in environments where multiple I/O-bound tasks must be managed concurrently.

For example, the following Python function reads a file asynchronously:

import aiofiles
import asyncio
async def read_file():
async with aiofiles.open("report.txt", "r") as file:
content = await file.read()
print("File content loaded.")
asyncio.run(read_file())

Here, the program can continue doing other tasks while the file is being read, making it ideal for I/O-heavy applications.

Back to the context of AI agents, the concept of synchronous and asynchronous calls go hand in hand with the tools’ calling mechanisms.

Figure 5.4: Example of synchronous and asynchronous processes in the context of AI agents

Figure 5.4: Example of synchronous and asynchronous processes in the context of AI agents

In a synchronous process, the agent makes a request and waits for a response before doing anything else. It cannot move on until the response arrives.

In AI workflows, this is typically fine for short-running, predictable tasks such as the following:

  • Converting units (e.g., Celsius to Fahrenheit)
  • Formatting dates or numbers
  • Simple database lookups
  • Calling fast APIs (e.g., local microservices)

With asynchronous calls, the agent initiates the call but doesn’t block it; the agent moves on and processes the result whenever it arrives.

This is especially useful when doing the following:

  • Calling slow or high-latency APIs (e.g., third-party services, external databases)
  • Performing I/O-bound operations (e.g., file uploads, web scraping)
  • Running multiple calls in parallel (e.g., batch data lookups)

Asynchronous tools make your agent more responsive and allow it to work on multiple things at once, improving performance and user experience.

The choice between sync and async is more than just an implementation detail—it directly affects the behavior of your agent:

  • Responsiveness: Async tools allow the agent to remain responsive even while waiting on long-running operations
  • Parallelism: Async calls can be batched or run concurrently, especially useful when retrieving from multiple sources
  • Error handling: Async tools can incorporate retry logic, fallbacks, or timeouts without freezing the agent.

Let’s look at a scenario. Suppose your agent needs to summarize weekly sales reports from five regional systems. A synchronous version would fetch them one by one—taking 5x the time. An async version would fetch them all at once.

@tool
async def fetch_sales_report(region: str) -> str:
"""Fetches the weekly sales report for a given region."""
await asyncio.sleep(2) # Simulated network delay
return f"{region} sales report: total sales $100k"
async def fetch_all_reports():
regions = ["North", "South", "East", "West", "Central"]
tasks = [fetch_sales_report(region) for region in regions]
results = await asyncio.gather(*tasks)
return "\n".join(results)

The async pattern allows the agent to retrieve all five reports in roughly the time it takes to fetch just one.

So, the question is: which method should I use? Typically, you might want to go with synchronous calls when operations are fast and blocking and won’t degrade the user experience, or tasks must be executed in a strict sequence, and each step depends on the previous one’s outcome. However, if you are dealing with high-latency operations where waiting would be inefficient and/or the agent needs to handle multiple tasks simultaneously, the asynchronous call is the go-to method.

Many AI systems will mix synchronous and asynchronous tools. That’s perfectly fine. What’s important is to design tools intentionally—knowing which tasks can block and which should be non-blocking.

Frameworks such as LangChain and Semantic Kernel support both patterns, often requiring you to register tools appropriately so the agent runtime can handle them.

As AI systems evolve from simple language processors into autonomous agents capable of reasoning, planning, and acting, the role of external tools and integrations becomes indispensable. Language models alone can interpret and generate text, but it is through tools—whether APIs, databases, or domain-specific functions—that they gain the ability to interact with the real world. These integrations extend the model’s reach beyond its training data, enabling it to access real-time information, trigger external actions, and retrieve domain-specific knowledge. Whether synchronously or asynchronously, through symbolic queries or semantic search, tools provide the scaffolding that transforms a passive model into an active system. Ultimately, it is the thoughtful design and orchestration of these external components that define the intelligence, reliability, and utility of modern AI agents.

In the next chapter, we will see all of this in action, as we will build our first AI agent leveraging all the components discussed so far.