工具使用手册#

您也可以在colab中查看这本手册这里

⭐ 在Github上给我们点星,加入我们的Discord或关注我们的X

太长不看版:#

CAMEL允许AI代理通过集成自定义工具来扩展其能力,类似于人类使用工具突破自然限制的方式。本教程展示如何在CAMEL中设置和定制工具,从计算器等基础功能到创建多代理系统协同完成任务。您将学习如何为AI代理配备使用工具执行各种任务的能力,使其更强大且多功能。加入CAMEL-AI社区并探索丰富资源,推动AI开发的边界。准备好增强您的AI代理了吗?深入教程并开始构建。

‍目录:#

  • 简介

  • 单个代理的工具使用情况(自定义您自己的工具)

  • 具备工具使用能力的AI社会

  • 结论

介绍#

人类与动物的关键区别在于人类创造和使用工具的能力,这使我们能够突破自然限制改造世界。同样在人工智能领域,大型语言模型(LLMs)使智能体能够利用外部工具,作为其能力的延伸。这些工具每个都有特定的名称、用途、输入和输出,使智能体能够完成原本不可能完成的任务。

本教程将向您展示如何使用CAMEL集成的工具以及如何自定义您自己的工具。

单个代理的Tool使用情况#

单个代理可以利用多个工具来回答问题、执行操作或完成复杂任务。在这里,您将使用CAMEL中支持的工具包以及您自定义的工具来构建一个代理。

首先我们将以搜索工具为例来演示如何使用现有工具,但您也可以在下方查看CAMEL支持的其他一些工具。

[ ]:
!pip install "camel-ai[all]==0.2.16"
[2]:
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

导入必要的模块后,您需要设置您的OpenAI密钥。

[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: ··········

现在你已经完成了这一步,让我们以简单的数学计算器函数add和sub为例来自定义一个工具。当你定义自己的函数时,请确保参数名称和文档字符串清晰明了,这样代理就能根据你提供的函数信息理解这个函数的功能以及何时使用它。> 这只是为了演示自定义工具的使用,内置的MathToolkit已经包含了add和sub工具。

[4]:
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

将这两个自定义函数添加到CAMEL的FunctionTool列表中:

[5]:
from camel.toolkits import FunctionTool


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

然后您可以将来自CAMEL的工具和您自己定义的工具添加到工具列表中:

[6]:
tools_list = [
    # *MathToolkit().get_tools(),
    *SearchToolkit().get_tools(),
    *MATH_FUNCS,
]

接下来让我们设置代理参数并初始化ChatAgent来调用该工具:

[7]:
# Set the backend mode, this model should support tool calling
model=ModelFactory.create(
    model_platform=ModelPlatformType.OPENAI,
    model_type=ModelType.GPT_4O_MINI
)

# Set message for the assistant
assistant_sys_msg =  """You are a helpful assistant to do search task."""


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

这里我们为代理定义了两个测试提示,询问关于牛津大学的事实。代理需要利用搜索能力来了解牛津大学的建校时间,并通过计算技能估算出该大学的年龄。

[8]:
# 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)

让我们看看代理在回答上述问题时的表现。代理应该正确告诉你牛津大学的建校时间及其估计年龄!

[9]:
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.")]
[10]:
print(assistant_response_calculate.info['tool_calls'])
[FunctionCallingRecord(func_name='sub', args={'a': 2024, 'b': 1096}, result=928)]

AI 社会与工具使用#

现在您已经启用了单个代理使用工具的功能,但您肯定可以进一步扩展这个概念。让我们建立一个小型AI生态系统。这个设置将包含两个代理:用户代理和助手代理。助手代理就是我们刚刚配置好具备工具使用能力的那个。

[11]:
from camel.societies import RolePlaying
from camel.agents.chat_agent import FunctionCallingRecord
from camel.utils import print_text_animated
from colorama import Fore
[13]:
# 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,
        ),
        tools=tools_list,
    ),
    user_agent_kwargs=dict(
        model=ModelFactory.create(
            model_platform=ModelPlatformType.OPENAI,
            model_type=ModelType.GPT_4O_MINI,
        ),
    ),
    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"
    )

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

    # 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")


    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 believed to have evidence of teaching as early as 1096. This makes it the oldest university in the English-speaking world. To estimate its founding year, we can use 1096 as a reference point.

Next, we will add 10 years to this estimated founding year to fulfill the task requirements.

Next request.


AI User:

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


AI Assistant:

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

Solution: To calculate the current age of the University of Oxford in 2024 based on the estimated founding year of 1096, we subtract the founding year from the current year:

2024 - 1096 = 928

Thus, the current age of the University of Oxford in 2024 is 928 years.

Next, we will add 10 more years to this age as per the task requirements.

Next request.


AI User:

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


AI Assistant:

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

Solution: To find the final age of the University of Oxford after adding 10 years to its current age of 928 years, we perform the following calculation:

928 + 10 = 938

Therefore, the final age of the University of Oxford, after adding 10 years, is 938 years.

Next request.


AI User:

<CAMEL_TASK_DONE>


结论#

我们预计,如CAMEL所展示的AI智能体中自定义工具使用的集成将持续发展和扩展。这种方法不仅使智能体能够执行超出其原生能力的任务,还促进了多智能体系统中的协作。通过标准化工具使用接口,CAMEL简化了在各种AI应用中定制和部署工具的过程,既节省时间又增强了多功能性。要充分利用这些功能,请确保您的CAMEL-AI设置是最新的。立即深入教程,开始构建更强大的AI智能体吧!