How to Build AI Agents Using “Tool Use”?

Published on:

Introduction

Earlier than speaking about AI Brokers, It’s crucial to know the lifespan of a complicated language mannequin like GPT. A big language mannequin similar to GPT begins its lifespan with pretraining when it learns from an enormous corpus of textual knowledge to determine a fundamental grasp of the language. The subsequent step is supervised fine-tuning when the mannequin is improved for particular duties through the use of specified datasets to refine it. Through the use of constructive reinforcement to optimize the mannequin’s habits, reward modeling enhances efficiency basically and decision-making specifically. Lastly, the mannequin might be taught and alter dynamically via interactions because of reinforcement studying, honing its abilities to do varied duties extra precisely and adaptable. On this article, we will even be taught how one can construct AI Brokers utilizing “Device Use.”

Overview

  • Language fashions like GPT are developed via pretraining, supervised fine-tuning, reward modeling, and reinforcement studying.
  • Every part entails particular datasets, algorithms, mannequin changes, and evaluations to boost the mannequin’s capabilities.
  • Static fashions battle with offering real-time data, requiring common fine-tuning, which is resource-intensive and sometimes impractical.
  • Construct AI Brokers Utilizing “Device Use” in Agentic Workflow.
  • AI brokers with entry to exterior instruments can collect real-time knowledge, execute duties, and preserve context, enhancing accuracy and responsiveness.

GPT Assistant Coaching Pipeline

Every part of the mannequin’s growth—pretraining, supervised fine-tuning, reward modeling, and reinforcement studying—progresses via 4 important elements: Dataset, Algorithm, Mannequin, and Analysis.

Pretraining Section

Within the preliminary pretraining part, the mannequin ingests huge portions of uncooked web knowledge, totaling trillions of phrases. Whereas the info’s high quality might range, its sheer quantity is substantial however nonetheless falls wanting satisfying the mannequin’s starvation for extra. This part calls for vital {hardware} sources, together with GPUs, and months of intensive coaching. The method begins with initializing weights from scratch and updating them as studying progresses. Algorithms like language modeling predict the following token, forming the premise of the mannequin’s early phases.

- Advertisement -
AI Agents tools

Supervised High-quality-Tuning Section

Transferring to supervised fine-tuning, the main focus shifts to task-specific labeled datasets the place the mannequin refines its parameters to foretell correct labels for every enter. Right here, the datasets’ high quality is paramount, resulting in a discount in amount. Algorithms tailor coaching for duties similar to token prediction, culminating in a Supervised High-quality-Tuning (SFT) Mannequin. This part requires fewer GPUs and fewer time than pretraining because of enhanced dataset high quality.

Reward Modeling Section

Reward modeling follows, using algorithms like binary classification to boost mannequin efficiency based mostly on constructive reinforcement alerts. The ensuing Reward Modeling (RM) Mannequin undergoes additional enhancement via human suggestions or analysis.

Reinforcement Studying Section

Reinforcement studying optimizes the mannequin’s responses via iterative interactions with its setting, making certain adaptability to new data and prompts. Nonetheless, integrating real-world knowledge to maintain the mannequin up to date stays a problem.

The Problem of Actual-Time Information

Addressing this problem entails bridging the hole between skilled knowledge and real-world data. It necessitates methods to repeatedly replace and combine new knowledge into the mannequin’s information base, making certain it may well reply precisely to the most recent queries and prompts.

- Advertisement -

Nonetheless, a important query arises: Whereas we’ve skilled our LLM on the info supplied, how will we equip it to entry and reply to real-world data, particularly to deal with the most recent queries and prompts?

As an example, the mannequin struggled to supply responses grounded in real-world knowledge when testing ChatGPT 3.5 with particular questions, as proven within the picture beneath:

Build AI Agents

High-quality-tune the Mannequin

One method is to fine-tune the mannequin, maybe scheduling each day classes commonly. Nonetheless, because of useful resource limitations, the viability of this system is at the moment beneath doubt. Common fine-tuning comes with a number of difficulties:

  1. Inadequate Information: An absence of recent knowledge steadily makes it not possible to justify quite a few fine-tuning classes.
  2. Excessive Necessities for Computation: High-quality-tuning normally requires vital processing energy, which could not be possible for normal duties.
  3. Time Intensiveness: Retraining the mannequin may take a protracted interval, which is an enormous impediment.

In gentle of those difficulties, it’s clear that including new knowledge to the mannequin requires overcoming a number of limitations and isn’t a easy operation.

So right here comes AI Brokers 

Right here, we current AI brokers, primarily LLMs, with built-in entry to exterior instruments. These brokers can accumulate and course of data, perform duties, and maintain monitor of previous encounters of their working reminiscence. Though acquainted LLM-based methods are able to operating programming and conducting net searches, AI brokers go one step additional:

  • Exterior Device Use: AI brokers can interface with and make the most of exterior instruments.
  • Information Gathering and Manipulation: They’ll accumulate and course of knowledge to assist them with their duties.
  • Job Planning: They’ll plan and perform duties delegated to those brokers.
  • Working Reminiscence: They maintain particulars from earlier exchanges, which improves dialogue movement and context.
  • Characteristic Enhancements: The vary of what LLMs can accomplish is elevated by this characteristic enhancement, which fits past fundamental questions and solutions to actively manipulating and leveraging exterior sources

Utilizing AI Brokers for Actual-Time Info Retrieval

If prompted with “What’s the present temperature and climate in Delhi, India?” a web based LLM-based chat system may provoke an online search to collect related data. Early on, builders of LLMs acknowledged that relying solely on pre-trained transformers to generate output is limiting. By integrating an online search device, LLMs can carry out extra complete duties. On this state of affairs, the LLM could possibly be fine-tuned or prompted (doubtlessly with few-shot studying) to generate a selected command like {device: web-search, question: “present temperature and climate in Delhi, India”} to provoke a search engine question.

See also  Google tops the Index with Gemini Live and Pixel's AI features

A subsequent step identifies such instructions, triggers the online search perform with the suitable parameters, retrieves the climate data, and integrates it again into the LLM’s enter context for additional processing.

- Advertisement -

Dealing with Advanced Queries with Computational Instruments

For those who pose a query similar to, “If a product-based firm sells an merchandise at a 20% loss, what could be the ultimate revenue or loss?” an LLM geared up with a code execution device may deal with this by executing a Python command to compute the outcome precisely. As an example, it would generate a command like {device: python-interpreter, code: “cost_price * (1 – 0.20)”}, the place “cost_price” represents the preliminary price of the merchandise. This method ensures that the LLM leverages computational instruments successfully to supply the proper revenue or loss calculation slightly than trying to generate the reply instantly via its language processing capabilities, which could not yield correct outcomes. Moreover that, with the assistance of exterior instruments, the customers may guide a ticket, which is planning an execution, i.e., Job Planning – Agentic Workflow.

So, AI brokers may also help ChatGPT with the issue of not having any details about the most recent knowledge in the true world. We will present entry to the Web, the place it may well Google search and retrieve the highest matches. So right here, on this case, the device is the Web search.

When the AI identifies the need for present climate data in responding to a consumer’s question, it features a record of accessible instruments in its API request, indicating its entry to such capabilities. Upon recognizing the necessity to use get_current_weather, it generates a selected perform name with a delegated location, similar to “London,” because the parameter. Subsequently, the system executes this perform name, fetching the most recent climate particulars for London. The retrieved climate knowledge is then seamlessly built-in into the AI’s response, enhancing the accuracy and relevance of the data supplied to the consumer.

Now, let’s implement and inculcate the Device Use to know the Agentic workflow!

We’re going to Use AI brokers, a device, to get data on present climate. As we noticed within the above instance, it can not generate a response to the real-world query utilizing the most recent knowledge. 

So, we’ll now start with the Implementation.

Let’s start:

Putting in dependencies and Libraries 

Let’s set up dependencies first:

langchain
langchain-community>=0.0.36
langchainhub>=0.1.15
llama_cpp_python  # please set up the proper construct based mostly in your {hardware} and OS
pandas
loguru
googlesearch-python
transformers
Openai

Importing Libraries 

Now, we’ll import libraries:

from openai import OpenAI
import json
from wealthy import print


import dotenv
dotenv.load_dotenv()

Preserve your OpenAI API key in an env file, or you’ll be able to put the important thing in a variable 

OPENAI_API_KEY= "your_open_api_key"

consumer = OpenAI(api_key= OPENAI_API_KEY)

Work together with the GPT mannequin utilizing code and never interface : 

messages = [{"role": "user", "content": "What's the weather like in London?"}]
response = consumer.chat.completions.create(
   mannequin="gpt-4o",
   messages=messages,
)
print(response)

This code units up a easy interplay with an AI mannequin, asking in regards to the climate in London. The API would course of this request and return a response, which you’d have to parse to get the precise reply.

It’s value noting that this code doesn’t fetch real-time climate knowledge. As an alternative, it asks an AI mannequin to generate a response based mostly on its coaching knowledge, which can not mirror the present climate in London.

AI Agents

On this case, the AI acknowledged it couldn’t present real-time data and urged checking a climate web site or app for present London climate.

This construction permits straightforward parsing and extracting related data from the API response. The extra metadata (like token utilization) could be helpful for monitoring and optimizing API utilization.

Defining the Operate

Now, let’s outline a perform for getting climate data and arrange the construction for utilizing it as a device in an AI dialog:

def get_current_weather(location):
   """Get the present climate in a given metropolis"""
   if "london" in location.decrease():
       return json.dumps({"temperature": "20 C"})
   elif "san francisco" in location.decrease():
       return json.dumps({"temperature": "15 C"})
   elif "paris" in location.decrease():
       return json.dumps({"temperature": "22 C"})
   else:
       return json.dumps({"temperature": "unknown"})

messages = [{"role": "user", "content": "What's the weather like in London?"}]
instruments = [
   {
       "type": "function",
       "function": {
           "name": "get_current_weather",
           "description": "Get the current weather in a given location",
           "parameters": {
               "type": "object",
               "properties": {
                   "location": {
                       "type": "string",
                       "description": "The city and state, e.g. San Francisco",
                   },
               },
               "required": ["location"],
           },
       },
   }
]

Code Clarification

This code snippet defines a perform for getting climate data and units up the construction for utilizing it as a device in an AI dialog. Let’s break it down:

  • get_current_weather perform:
    • Takes a location parameter.
    • Returns simulated climate knowledge for London, San Francisco, and Paris.
    • For some other location, it returns “unknown”.
    • The climate knowledge is returned as a JSON string.
  • messages record:
    • Accommodates a single message from the consumer asking in regards to the climate in London.
    • This is similar as within the earlier instance.
  • instruments record:
    • Defines a single device (perform) that the AI can use.
    • The device is of sort “perform”.
    • It describes the get_current_weather perform:
      • identify: The identify of the perform to be referred to as.
      • description: A short description of what the perform does.
      • parameters: Describes the anticipated enter for the perform:
        • It expects an object with a location property.
        • location ought to be a string describing a metropolis.
        • The placement parameter is required.
response = consumer.chat.completions.create(
   mannequin="gpt-4o",
   messages=messages,
   instruments=instruments,
)
print(response)
Build AI Agents

Additionally learn: Agentic AI Demystified: The Final Information to Autonomous Brokers

See also  Here’s everything Apple announced at the WWDC 2024 keynote, including Apple Intelligence, Siri makeover

Right here, we use three exterior Scripts named LLMs, instruments, and tool_executor, which act as helper capabilities.

fromllms import OpenAIChatCompletion
from instruments import get_current_weather
from tool_executor import need_tool_use

Earlier than going additional with the code movement, let’s perceive the scripts.

llms.py script

It manages interactions with OpenAI’s chat completion API, enabling using exterior instruments throughout the chat context:

from typing import Listing, Non-obligatory, Any, Dict

import logging
from brokers.specs import ChatCompletion
from brokers.tool_executor import ToolRegistry
from langchain_core.instruments import StructuredTool
from llama_cpp import ChatCompletionRequestMessage
from openai import OpenAI

logger = logging.getLogger(__name__)

class OpenAIChatCompletion:
   def __init__(self, mannequin: str = "gpt-4o"):
       self.mannequin = mannequin
       self.consumer = OpenAI()
       self.tool_registry = ToolRegistry()

   def bind_tools(self, instruments: Non-obligatory[List[StructuredTool]] = None):
       for device in instruments:
           self.tool_registry.register_tool(device)


   def chat_completion(
       self, messages: Listing[ChatCompletionRequestMessage], **kwargs
   ) -> ChatCompletion:
       instruments = self.tool_registry.openai_tools
       output = self.consumer.chat.completions.create(
           mannequin=self.mannequin, messages=messages, instruments=instruments
       )
       logger.debug(output)
       return output


   def run_tools(self, chat_completion: ChatCompletion) -> Listing[Dict[str, Any]]:
       return self.tool_registry.call_tools(chat_completion)

This code defines a category OpenAIChatCompletion that encapsulates the performance for interacting with OpenAI’s chat completion API and managing instruments. Let’s break it down:

Imports

Varied typing annotations and essential modules are imported.

Class Definition

pythonCopyclass OpenAIChatCompletion:

This class serves as a wrapper for OpenAI’s chat completion performance.

Constructor

pythonCopydef __init__(self, mannequin: str = “gpt-4o”):

Initializes the category with a specified mannequin (default is “gpt-4o”).

Creates an OpenAI consumer and a ToolRegistry occasion.

bind_tools methodology

pythonCopydef bind_tools(self, instruments: Non-obligatory[List[StructuredTool]] = None):

Registers supplied instruments with the ToolRegistry.

This enables the chat completion to make use of these instruments when wanted.

chat_completion methodology:

pythonCopydef chat_completion(

    self, messages: Listing[ChatCompletionRequestMessage], **kwargs

) ->

ChatCompletion

Sends a request to the OpenAI API for chat completion.

Consists of the registered instruments within the request.

Returns the API response as a ChatCompletion object.

run_tools methodology

pythonCopydef run_tools(self, chat_completion: ChatCompletion) -> Listing[Dict[str, Any]]:

Executes the instruments referred to as within the chat completion response.

Returns the outcomes of the device executions.

instruments.py

It defines particular person instruments or capabilities, similar to fetching real-time climate knowledge, that may be utilized by the AI to carry out particular duties.

import json
import requests
from langchain.instruments import device
from loguru import logger

@device
def get_current_weather(metropolis: str) -> str:
   """Get the present climate for a given metropolis.


   Args:
     metropolis (str): Town to fetch climate for.


   Returns:
     str: present climate situation, or None if an error happens.
   """
   strive:
       knowledge = json.dumps(
           requests.get(f"https://wttr.in/{metropolis}?format=j1")
           .json()
           .get("current_condition")[0]
       )
       return knowledge
   besides Exception as e:
       logger.exception(e)
       error_message = f"Error fetching present climate for {metropolis}: {e}"
       return error_message

This code defines a number of instruments that can be utilized in an AI system, doubtless together with the OpenAIChatCompletion class we mentioned earlier. Let’s break down every device:

get_current_weather:

  • Fetches real-time climate knowledge for a given metropolis utilizing the wttr.in API.
  • Returns the climate knowledge as a JSON string.
  • Consists of error dealing with and logging.

Tool_executor.py

It handles the execution and administration of instruments, making certain they’re referred to as and built-in appropriately throughout the AI’s response workflow.

import json
from typing import Any, Listing, Union, Dict

from langchain_community.instruments import StructuredTool

from langchain_core.utils.function_calling import convert_to_openai_function
from loguru import logger
from brokers.specs import ChatCompletion, ToolCall

class ToolRegistry:
   def __init__(self, tool_format="openai"):
       self.tool_format = tool_format
       self._tools: Dict[str, StructuredTool] = {}
       self._formatted_tools: Dict[str, Any] = {}

   def register_tool(self, device: StructuredTool):
       self._tools[tool.name] = device
       self._formatted_tools[tool.name] = convert_to_openai_function(device)

   def get(self, identify: str) -> StructuredTool:
       return self._tools.get(identify)

   def __getitem__(self, identify: str)
       return self._tools[name]

   def pop(self, identify: str) -> StructuredTool:
       return self._tools.pop(identify)

   @property
   def openai_tools(self) -> Listing[Dict[str, Any]]:
       # [{"type": "function", "function": registry.openai_tools[0]}],
       outcome = []
       for oai_tool in self._formatted_tools.values():
           outcome.append({"sort": "perform", "perform": oai_tool})

       return outcome if outcome else None

   def call_tool(self, device: ToolCall) -> Any:
       """Name a single device and return the outcome."""
       function_name = device.perform.identify
       function_to_call = self.get(function_name)


       if not function_to_call:
           increase ValueError(f"No perform was discovered for {function_name}")


       function_args = json.hundreds(device.perform.arguments)
       logger.debug(f"Operate {function_name} invoked with {function_args}")
       function_response = function_to_call.invoke(function_args)
       logger.debug(f"Operate {function_name}, responded with {function_response}")
       return function_response

   def call_tools(self, output: Union[ChatCompletion, Dict]) -> Listing[Dict[str, str]]:
       """Name all instruments from the ChatCompletion output and return the
       outcome."""
       if isinstance(output, dict):
           output = ChatCompletion(**output)


       if not need_tool_use(output):
           increase ValueError(f"No device name was present in ChatCompletionn{output}")

       messages = []
       # https://platform.openai.com/docs/guides/function-calling
       tool_calls = output.decisions[0].message.tool_calls
       for device in tool_calls:
           function_name = device.perform.identify
           function_response = self.call_tool(device)
           messages.append({
               "tool_call_id": device.id,
               "position": "device",
               "identify": function_name,
               "content material": function_response,
           })
       return messages

def need_tool_use(output: ChatCompletion) -> bool:
   tool_calls = output.decisions[0].message.tool_calls
   if tool_calls:
       return True
   return False

def check_function_signature(
   output: ChatCompletion, tool_registry: ToolRegistry = None
):
   instruments = output.decisions[0].message.tool_calls
   invalid = False
   for device in instruments:
       device: ToolCall
       if device.sort == "perform":
           function_info = device.perform
           if tool_registry:
               if tool_registry.get(function_info.identify) is None:
                   logger.error(f"Operate {function_info.identify} shouldn't be out there")
                   invalid = True


           arguments = function_info.arguments
           strive:
               json.hundreds(arguments)
           besides json.JSONDecodeError as e:
               logger.exception(e)
               invalid = True
       if invalid:
           return False

   return True

Code Clarification

This code defines a ToolRegistry class and related helper capabilities for managing and executing instruments in an AI system. Let’s break it down:

  • ToolRegistry class:
    • Manages a group of instruments, storing them in each their authentic kind and an OpenAI-compatible format.
    • Supplies strategies to register, retrieve, and execute instruments.
  • Key strategies:
    • register_tool: Provides a brand new device to the registry.
    • openai_tools: Property that returns instruments in OpenAI’s perform format.
    • call_tool: Executes a single device.
    • call_tools: Executes a number of instruments from a ChatCompletion output.
  • Helper capabilities:
    • need_tool_use: Checks if a ChatCompletion output requires device utilization.
    • check_function_signature: Validates perform calls towards the out there instruments.
See also  iPhone 16 Pro vs. iPhone 14 Pro: Is it worth an upgrade?

This ToolRegistry class is a central part for managing and executing instruments in an AI system. It permits for:

  • Straightforward registration of recent instruments
  • Conversion of instruments to OpenAI’s perform calling format
  • Execution of instruments based mostly on AI mannequin outputs
  • Validation of device calls and signatures

The design permits seamless integration with AI fashions supporting perform calling, like these from OpenAI. It gives a structured approach to lengthen an AI system’s capabilities by permitting it to work together with exterior instruments and knowledge sources.

The helper capabilities need_tool_use and check_function_signature present further utility for working with ChatCompletion outputs and validating device utilization.

This code kinds an important half of a bigger system for constructing AI brokers able to utilizing exterior instruments and APIs to boost their capabilities past easy textual content technology.

These had been the exterior scripts and different helper capabilities required to incorporate exterior instruments/performance and leverage all AI capabilities.

Additionally learn: How Autonomous AI Brokers Are Shaping Our Future?

Now, an occasion of OpenAIChatCompletion is created.

The get_current_weather device is sure to this occasion.

A message record is created with a consumer question about London’s climate.

A chat completion is requested utilizing this setup.

llm = OpenAIChatCompletion()
llm.bind_tools([get_current_weather])

messages = [
   {"role": "user", "content": "how is the weather in London today?"}
]

output = llm.chat_completion(messages)
print(output)
AI Agents
  • The AI understood that to reply the query about London’s climate, it wanted to make use of the get_current_weather perform.
  • As an alternative of offering a direct reply, it requests that this perform be referred to as with “London” because the argument.
  • In an entire system, the following step could be to execute the get_current_weather perform with this argument, get the outcome, after which doubtlessly work together with the AI once more to formulate a closing response based mostly on the climate knowledge.

This demonstrates how the AI can intelligently resolve to make use of out there instruments to collect data earlier than offering a solution, making its responses extra correct and up-to-date.

if need_tool_use(output):
   print("Utilizing climate device")
   tool_results = llm.run_tools(output)
   print(tool_results)
   tool_results[0]["role"] = "assistant"


   updated_messages = messages + tool_results
   updated_messages = updated_messages + [
       {"role": "user", "content": "Think step by step and answer my question based on the above context."}
   ]
   output = llm.chat_completion(updated_messages)


print(output.decisions[0].message.content material)

This code:

  • Examine if instruments must be used based mostly on the AI’s output.
  • Runs the device (get_current_weather) and prints the outcome.
  • Adjustments the position of the device outcome to “assistant.”
  • Creates an up to date message record with the unique message, device outcomes, and a brand new consumer immediate.
  • Sends this up to date message record for one more chat completion.
AI Agents
  • The AI initially acknowledged it wanted climate knowledge to reply the query.
  • The code executed the climate device to get this knowledge.
  • The climate knowledge was added to the context of the dialog.
  • The AI was then prompted to reply the unique query utilizing this new data.
  • The ultimate response is a complete breakdown of London’s climate, instantly answering the unique query with particular, up-to-date data.

Conclusion

This implementation represents a major step towards creating extra succesful, context-aware AI methods. By bridging the hole between giant language fashions and exterior instruments and knowledge sources, we will create AI assistants that perceive and generate human-like textual content that meaningfully interacts with the true world.

Continuously Requested Questions

Q1. What precisely is an AI agent with dynamic device use?

Ans. An AI agent with dynamic device use is a complicated synthetic intelligence system that may autonomously choose and make the most of varied exterior instruments or capabilities to collect data, carry out duties, and clear up issues. Not like conventional chatbots or AI fashions which might be restricted to their pre-trained information, these brokers can work together with exterior knowledge sources and APIs in actual time, permitting them to supply up-to-date and contextually related responses.

Q2. How does utilizing a dynamic device differ from that of standard AI fashions?

Ans. Common AI fashions usually rely solely on their pre-trained information to generate responses. In distinction, AI brokers with dynamic device use can acknowledge after they want further data, choose acceptable instruments to collect that data (like climate APIs, engines like google, or databases), use these instruments, after which incorporate the brand new knowledge into their reasoning course of. This enables them to deal with a a lot wider vary of duties and supply extra correct, present data.

Q3. What are the potential purposes of constructing AI brokers with device use?

Ans. The purposes of constructing AI brokers are huge and different. Some examples embrace:
– Private assistants who can schedule appointments, test real-time data, and carry out complicated analysis duties.
– Customer support bots that may entry consumer accounts, course of orders, and supply product data.
– Monetary advisors who can analyze market knowledge, test present inventory costs, and supply customized funding recommendation.
– Healthcare assistants who can entry medical databases interpret lab outcomes and supply preliminary diagnoses.
– Undertaking administration methods that may coordinate duties, entry a number of knowledge sources, and supply real-time updates.

- Advertisment -

Related

- Advertisment -

Leave a Reply

Please enter your comment!
Please enter your name here