Tools Cookbook#

You can also check this cookbook in colab here

TLDR:#

CAMEL allows AI agents to extend their capabilities by integrating custom tools, similar to how humans use tools to surpass natural limits. This tutorial shows how to set up and customize tools within CAMEL, from basic functions like calculators to creating multi-agent systems that collaborate on tasks. You’ll learn to equip AI agents with the ability to use tools for various tasks, making them more powerful and versatile. Engage with the CAMEL-AI community and explore extensive resources to push the boundaries of AI development. Ready to enhance your AI agents? Dive into the tutorial and start building.

‍Table of Content:#

  • Introduction

  • Tool Usage of a Single Agent (Customize Your Own Tools)

  • AI Society with Tool Usage

  • Conclusion

Introduction#

The key difference between humans and animals lies in the human ability to create and use tools, allowing us to shape the world beyond natural limits. Similarly, in AI, Large Language Models (LLMs) enable agents to utilize external tools, acting as extensions of their capabilities. These tools, each with a specific name, purpose, input, and output, empower agents to perform tasks otherwise impossible.

This tutorial will show you how to use tools integrated by CAMEL and how to customize your own tools.

Tool Usage of a Single Agent#

A single agent can utilize multiple tools to answer questions, take actions, or perform complex tasks. Here you will build an agent using both the supported toolkit in CAMEL and the tool customized by you.

First we are going to take the search tool as an example for utilizing existing tools but you can also see some of the other tools supported by CAMEL below.

[ ]:
%pip install "camel-ai[all]==0.2.1"
[18]:
from camel.agents import ChatAgent
from camel.configs import ChatGPTConfig
from camel.toolkits import (
    SearchToolkit,
    MathToolkit,
    # GoogleMapsToolkit,
    # TwitterToolkit,
    # WeatherToolkit,
    # RetrievalToolkit,
    # TwitterToolkit,
    # SlackToolkit,
    # LinkedInToolkit,
    # RedditToolkit,
)
from camel.messages import BaseMessage
from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType

After importing necessary modules, you need to set up your OpenAI key.

[3]:
import os
from getpass import getpass

# Prompt for the API key securely
openai_api_key = getpass('Enter your API key: ')
os.environ["OPENAI_API_KEY"] = openai_api_key
Enter your API key: ··········

Now you have done that, let’s customize a tool by taking the simple math calculator, functions add and sub, as an example. When you define your own function, make sure the argument name and docstring are clear so that the agent can understand what this function can do and when to use the function based on the function information you provide.

[19]:

def add(a: int, b: int) -> int: r"""Adds two numbers. Args: a (int): The first number to be added. b (int): The second number to be added. Returns: integer: The sum of the two numbers. """ return a + b def sub(a: int, b: int) -> int: r"""Do subtraction between two numbers. Args: a (int): The minuend in subtraction. b (int): The subtrahend in subtraction. Returns: integer: The result of subtracting :obj:`b` from :obj:`a`. """ return a - b

Add these 2 customized functions as CAMEL’s OpenAIFunction list:

[20]:
from camel.toolkits import OpenAIFunction


MATH_FUNCS: list[OpenAIFunction] = [
    OpenAIFunction(func) for func in [add, sub]
]

Then you can add the tool from CAMEL and the one defined by yourself to the tool list:

[21]:
tools_list = [
    *MathToolkit().get_tools(),
    *SearchToolkit().get_tools(),
]

Next let’s set the parameters to the agent and initianize ChatAgent to call the tool:

[22]:
# Set the backend mode, this model should support tool calling
model=ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O_MINI,
    model_config_dict=ChatGPTConfig(
        temperature=0.0,
    ).as_dict(),
)

# Set message for the assistant
assistant_sys_msg = BaseMessage.make_assistant_message(
    role_name="Search Agent",
    content= """You are a helpful assistant to do search task."""
)

# Set the config parameter for the model
assistant_model_config = ChatGPTConfig(
    temperature=0.0,
)

# Set the agent
agent = ChatAgent(
    assistant_sys_msg,
    model=model,
    tools=tools_list
)


Here we define two test prompts for the agent, asking about the facts about University of Oxford. Here the agent needs to take advantage of the searching capability to know when University of Oxford is founded and the calculating skills to obtain the estimated age of the Uni.

[23]:
# Set prompt for the search task
prompt_search = ("""When was University of Oxford set up""")
# Set prompt for the calculation task
prompt_calculate = ("""Assume now is 2024 in the Gregorian calendar, University of Oxford was set up in 1096, estimate the current age of University of Oxford""")

# Convert the two prompt as message that can be accepted by the Agent
user_msg_search = BaseMessage.make_user_message(role_name="User", content=prompt_search)
user_msg_calculate = BaseMessage.make_user_message(role_name="User", content=prompt_calculate)

# Get response
assistant_response_search = agent.step(user_msg_search)
assistant_response_calculate = agent.step(user_msg_calculate)

Let’s see the agent’ performance for answering above questions. The agent should tell you correctly when University of Oxford was set up and its estimated age!

[24]:
print(assistant_response_search.info['tool_calls'])
[FunctionCallingRecord(func_name='search_wiki', args={'entity': 'University of Oxford'}, result="The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.")]
[25]:
print(assistant_response_calculate.info['tool_calls'])
[FunctionCallingRecord(func_name='sub', args={'a': 2024, 'b': 1096}, result=928)]

AI Society with Tool Usage#

Now you’ve enabled a single agent to utilize tools, but you can surelytake this concept further. Let’s establish a small AI ecosystem. This setup will consist of two agents: a user agent and an assistant agent. The assistant agent will be the one we’ve just configured with tool-using capabilities.

[26]:
from camel.societies import RolePlaying
from camel.agents.chat_agent import FunctionCallingRecord
from camel.utils import print_text_animated
from colorama import Fore
[27]:
# Set a task
task_prompt=("Assume now is 2024 in the Gregorian calendar, "
        "estimate the current age of University of Oxford "
        "and then add 10 more years to this age.")

# Set role playing
role_play_session = RolePlaying(
    assistant_role_name="Searcher",
    user_role_name="Professor",
    assistant_agent_kwargs=dict(
        model=ModelFactory.create(
            model_platform=ModelPlatformType.OPENAI,
            model_type=ModelType.GPT_4O_MINI,
            model_config_dict=assistant_model_config.as_dict(),
        ),
        tools=tools_list,
    ),
    user_agent_kwargs=dict(
        model=ModelFactory.create(
            model_platform=ModelPlatformType.OPENAI,
            model_type=ModelType.GPT_4O_MINI,
            model_config_dict=ChatGPTConfig(temperature=0.0).as_dict(),
        ),
    ),
    task_prompt=task_prompt,
    with_task_specify=False,
)

# Set the limit for the chat turn
chat_turn_limit=10

print(
    Fore.GREEN
    + f"AI Assistant sys message:\n{role_play_session.assistant_sys_msg}\n"
)
print(
    Fore.BLUE + f"AI User sys message:\n{role_play_session.user_sys_msg}\n"
)

print(Fore.YELLOW + f"Original task prompt:\n{task_prompt}\n")
print(
    Fore.CYAN
    + "Specified task prompt:"
    + f"\n{role_play_session.specified_task_prompt}\n"
)
print(Fore.RED + f"Final task prompt:\n{role_play_session.task_prompt}\n")

n = 0
input_msg = role_play_session.init_chat()
while n < chat_turn_limit:
    n += 1
    assistant_response, user_response = role_play_session.step(input_msg)

    if assistant_response.terminated:
        print(
            Fore.GREEN
            + (
                "AI Assistant terminated. Reason: "
                f"{assistant_response.info['termination_reasons']}."
            )
        )
        break
    if user_response.terminated:
        print(
            Fore.GREEN
            + (
                "AI User terminated. "
                f"Reason: {user_response.info['termination_reasons']}."
            )
        )
        break

    # Print output from the user
    print_text_animated(
        Fore.BLUE + f"AI User:\n\n{user_response.msg.content}\n"
    )

    # Print output from the assistant, including any function
    # execution information
    print_text_animated(Fore.GREEN + "AI Assistant:")
    tool_calls: list[FunctionCallingRecord] = assistant_response.info[
        'tool_calls'
    ]
    for func_record in tool_calls:
        print_text_animated(f"{func_record}")
    print_text_animated(f"{assistant_response.msg.content}\n")

    if "CAMEL_TASK_DONE" in user_response.msg.content:
        break

    input_msg = assistant_response.msg
AI Assistant sys message:
BaseMessage(role_name='Searcher', role_type=<RoleType.ASSISTANT: 'assistant'>, meta_dict={'task': 'Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.', 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF ASSISTANT =====\nNever forget you are a Searcher and I am a Professor. Never flip roles! Never instruct me!\nWe share a common interest in collaborating to successfully complete a task.\nYou must help me to complete the task.\nHere is the task: Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.. Never forget our task!\nI must instruct you based on your expertise and my needs to complete the task.\n\nI must give you one instruction at a time.\nYou must write a specific solution that appropriately solves the requested instruction and explain your solutions.\nYou must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.\nUnless I say the task is completed, you should always start with:\n\nSolution: <YOUR_SOLUTION>\n\n<YOUR_SOLUTION> should be very specific, include detailed explanations and provide preferable detailed implementations and examples and lists for task-solving.\nAlways end <YOUR_SOLUTION> with: Next request.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')

AI User sys message:
BaseMessage(role_name='Professor', role_type=<RoleType.USER: 'user'>, meta_dict={'task': 'Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.', 'assistant_role': 'Searcher', 'user_role': 'Professor'}, content='===== RULES OF USER =====\nNever forget you are a Professor and I am a Searcher. Never flip roles! You will always instruct me.\nWe share a common interest in collaborating to successfully complete a task.\nI must help you to complete the task.\nHere is the task: Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.. Never forget our task!\nYou must instruct me based on my expertise and your needs to solve the task ONLY in the following two ways:\n\n1. Instruct with a necessary input:\nInstruction: <YOUR_INSTRUCTION>\nInput: <YOUR_INPUT>\n\n2. Instruct without any input:\nInstruction: <YOUR_INSTRUCTION>\nInput: None\n\nThe "Instruction" describes a task or question. The paired "Input" provides further context or information for the requested "Instruction".\n\nYou must give me one instruction at a time.\nI must write a response that appropriately solves the requested instruction.\nI must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.\nYou should instruct me not ask me questions.\nNow you must start to instruct me using the two ways described above.\nDo not add anything else other than your instruction and the optional corresponding input!\nKeep giving me instructions and necessary inputs until you think the task is completed.\nWhen the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.\nNever say <CAMEL_TASK_DONE> unless my responses have solved your task.', video_bytes=None, image_list=None, image_detail='auto', video_detail='low')

Original task prompt:
Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.

Specified task prompt:
None

Final task prompt:
Assume now is 2024 in the Gregorian calendar, estimate the current age of University of Oxford and then add 10 more years to this age.

AI User:

Instruction: Estimate the founding year of the University of Oxford.
Input: None


AI Assistant:

Function Execution: search_wiki
        Args: {'entity': 'University of Oxford'}
        Result: The University of Oxford is a collegiate research university in Oxford, England. There is evidence of teaching as early as 1096, making it the oldest university in the English-speaking world and the world's second-oldest university in continuous operation. It grew rapidly from 1167, when Henry II banned English students from attending the University of Paris. After disputes between students and Oxford townsfolk, some Oxford academics fled northeast to Cambridge, where, in 1209, they established the University of Cambridge. The two English ancient universities share many common features and are jointly referred to as Oxbridge.

Solution: The University of Oxford is estimated to have evidence of teaching as early as 1096. This makes it the oldest university in the English-speaking world and the second-oldest university in continuous operation globally.

Next, we will add 10 years to this founding year of 1096 to complete the task.

Next request.


AI User:

Instruction: Calculate the current age of the University of Oxford in 2024 based on the founding year of 1096.
Input: None


AI Assistant:

Function Execution: sub
        Args: {'a': 2024, 'b': 1096}
        Result: 928

Solution: The current age of the University of Oxford in 2024, based on the founding year of 1096, is calculated as follows:

Current Year (2024) - Founding Year (1096) = Age
2024 - 1096 = 928 years

Therefore, the University of Oxford is 928 years old in 2024.

Next, we will add 10 more years to this age to complete the task.

Next request.


AI User:

Instruction: Add 10 years to the current age of the University of Oxford (928 years).
Input: None


AI Assistant:

Function Execution: add
        Args: {'a': 928, 'b': 10}
        Result: 938

Solution: Adding 10 years to the current age of the University of Oxford (928 years) is calculated as follows:

Current Age (928 years) + Additional Years (10 years) = New Age
928 + 10 = 938 years

Therefore, after adding 10 years, the estimated age of the University of Oxford will be 938 years in 2034.

Next request.


AI User:

Instruction: Summarize the final estimated age of the University of Oxford after adding 10 years.
Input: None


AI Assistant:

Solution: The final estimated age of the University of Oxford, after adding 10 years to its current age of 928 years, is 938 years. This means that in the year 2034, the University of Oxford will be 938 years old.

Next request.


AI User:

Instruction: Confirm that the task is completed based on the provided solutions.
Input: None


AI Assistant:

Solution: The task is confirmed as completed. We have successfully estimated the current age of the University of Oxford as 928 years in 2024 and added 10 years to arrive at a final estimated age of 938 years in 2034.

If you have any further requests or tasks, please let me know!

Next request.


AI User:

<CAMEL_TASK_DONE>


AI Assistant:

Solution: The task is marked as done. If you have any other tasks or inquiries in the future, feel free to reach out.

Next request.


Conclusion#

We anticipate that the integration of custom tool usage within AI agents, as demonstrated through CAMEL, will continue to evolve and expand. This approach not only empowers agents to perform tasks beyond their native capabilities but also fosters collaboration in multi-agent systems. By standardizing the interface for tool usage, CAMEL simplifies the process of customizing and deploying tools across various AI applications, saving time and enhancing versatility. To fully utilize these capabilities, ensure your CAMEL-AI setup is up to date. Dive into the tutorial and start building more powerful AI agents today!