自学内容网 自学内容网

5. Autogen官网教程 (Tool Use)

简介

工具是agent可以调用的预定义函数。代理不必编写任意代码,而是可以调用工具来执行动作,比如搜索网络、执行计算、读取文件或调用远程API。因为你能够控制提供给代理的工具,所以你能控制代理能够执行的动作。

1. 定义计算器函数

首先,我们需要定义一个计算器函数,它接受两个整数和一个操作符,然后返回计算结果。

from typing import Annotated, Literal

Operator = Literal["+", "-", "*", "/"]


def calculator(a: int, b: int, operator: Annotated[Operator, "operator"]) -> int:
    if operator == "+":
        return a + b
    elif operator == "-":
        return a - b
    elif operator == "*":
        return a * b
    elif operator == "/":
        return int(a / b)
    else:
        raise ValueError("Invalid operator")

2. 创建对话代理

接下来,我们使用 autogen 库创建两个对话代理:一个助手代理和一个用户代理。

import os

from autogen import ConversableAgent


llm_config = { "config_list": [{ "model": "GLM-4-Plus", 
                                "api_key": "your api key", 
                                "base_url":"https://open.bigmodel.cn/api/paas/v4/"
                                }] }

# 创建助手代理
assistant = ConversableAgent(
    name="Assistant",
    system_message="You are a helpful AI assistant. "
    "You can help with simple calculations."
    "Remember returning 'TERMINATE' when the task is done. Just like this one, The result is ... TERMINATE",
    llm_config=llm_config,
)

# 创建用户代理
user_proxy = ConversableAgent(
    name="User",
    llm_config=False,
    is_termination_msg=lambda msg: msg.get("content") is not None and "TERMINATE" in msg["content"],
    human_input_mode="NEVER",
)

3. 注册计算器工具

我们将计算器函数注册到助手代理和用户代理中。

# 注册计算器函数到助手代理
assistant.register_for_llm(name="calculator", description="A simple calculator")(calculator)

# 注册计算器函数到用户代理
user_proxy.register_for_execution(name="calculator")(calculator)

另一种注册方式:

from autogen import register_function

# Register the calculator function to the two agents.
register_function(
    calculator,
    caller=assistant,  # The assistant agent can suggest calls to the calculator.
    executor=user_proxy,  # The user proxy agent can execute the calculator calls.
    name="calculator",  # By default, the function name is used as the tool name.
    description="A simple calculator",  # A description of the tool.
)
d:\soft\anaconda\envs\autogen\Lib\site-packages\autogen\agentchat\conversable_agent.py:2585: UserWarning: Function 'calculator' is being overridden.
  warnings.warn(f"Function '{tool_sig['function']['name']}' is being overridden.", UserWarning)
d:\soft\anaconda\envs\autogen\Lib\site-packages\autogen\agentchat\conversable_agent.py:2504: UserWarning: Function 'calculator' is being overridden.
  warnings.warn(f"Function '{name}' is being overridden.", UserWarning)

4. 使用计算器工具

现在,我们可以使用用户代理发起对话,并询问助手代理进行计算。

chat_result = user_proxy.initiate_chat(assistant, message="What is (44232 + 13312 / (232 - 32)) * 5?")

助手代理会自动调用计算器工具,并返回计算结果。

[33mUser[0m (to Assistant):

What is (44232 + 13312 / (232 - 32)) * 5?

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:15:31] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217975049170105444): calculator *****[0m
Arguments: 
{"a": 44232, "b": 13312, "operator": "+"}
[32m***********************************************************************[0m
[32m***** Suggested tool call (call_-9217975049170105443): calculator *****[0m
Arguments: 
{"a": 232, "b": 32, "operator": "-"}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217975049170105444) *****[0m
57544
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217975049170105443) *****[0m
200
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:15:31] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217971235238016078): calculator *****[0m
Arguments: 
{"a": 13312, "b": 200, "operator": "/"}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217971235238016078) *****[0m
66
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:15:33] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217971063439119888): calculator *****[0m
Arguments: 
{"a": 44232, "b": 66, "operator": "+"}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217971063439119888) *****[0m
44298
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:15:33] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217974465053955698): calculator *****[0m
Arguments: 
{"a": 44298, "b": 5, "operator": "*"}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217974465053955698) *****[0m
221490
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:15:34] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

The result is 221490. TERMINATE

--------------------------------------------------------------------------------

Tool Schema

assistant.llm_config["tools"]
[{'type': 'function',
  'function': {'description': 'A simple calculator',
   'name': 'calculator',
   'parameters': {'type': 'object',
    'properties': {'a': {'type': 'integer', 'description': 'a'},
     'b': {'type': 'integer', 'description': 'b'},
     'operator': {'enum': ['+', '-', '*', '/'],
      'type': 'string',
      'description': 'operator'}},
    'required': ['a', 'b', 'operator']}}}]

5. 改进计算器工具

为了更好地处理嵌套表达式,我们可以将计算器函数的输入参数改为一个包含所有信息的对象。

from pydantic import BaseModel, Field


class CalculatorInput(BaseModel):
    a: Annotated[int, Field(description="The first number.")]
    b: Annotated[int, Field(description="The second number.")]
    operator: Annotated[Operator, Field(description="The operator.")]


def calculator(input: Annotated[CalculatorInput, "Input to the calculator."]) -> int:
    if input.operator == "+":
        return input.a + input.b
    elif input.operator == "-":
        return input.a - input.b
    elif input.operator == "*":
        return input.a * input.b
    elif input.operator == "/":
        return int(input.a / input.b)
    else:
        raise ValueError("Invalid operator")

重新注册计算器工具,并再次发起对话进行测试。

assistant.register_for_llm(name="calculator", description="A calculator tool that accepts nested expression as input")(
    calculator
)
user_proxy.register_for_execution(name="calculator")(calculator)

chat_result = user_proxy.initiate_chat(assistant, message="What is (1423 - 123) / 3 + (32 + 23) * 5?")

Tool Schema

assistant.llm_config["tools"]
[{'type': 'function',
  'function': {'description': 'A calculator tool that accepts nested expression as input',
   'name': 'calculator',
   'parameters': {'type': 'object',
    'properties': {'input': {'properties': {'a': {'description': 'The first number.',
        'title': 'A',
        'type': 'integer'},
       'b': {'description': 'The second number.',
        'title': 'B',
        'type': 'integer'},
       'operator': {'description': 'The operator.',
        'enum': ['+', '-', '*', '/'],
        'title': 'Operator',
        'type': 'string'}},
      'required': ['a', 'b', 'operator'],
      'title': 'CalculatorInput',
      'type': 'object',
      'description': 'Input to the calculator.'}},
    'required': ['input']}}}]

助手代理会根据嵌套表达式调用计算器工具,并返回最终的计算结果。

[33mUser[0m (to Assistant):

What is (1423 - 123) / 3 + (32 + 23) * 5?

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:32] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217969001854210906): calculator *****[0m
Arguments: 
{"input": {"a": 1423, "b": 123, "operator": "-"}}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217969001854210906) *****[0m
1300
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:33] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217975289688536441): calculator *****[0m
Arguments: 
{"input": {"a": 1300, "b": 3, "operator": "/"}}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217975289688536441) *****[0m
433
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:34] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217971200878211977): calculator *****[0m
Arguments: 
{"input": {"a": 32, "b": 23, "operator": "+"}}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217971200878211977) *****[0m
55
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:35] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217974224535631038): calculator *****[0m
Arguments: 
{"input": {"a": 55, "b": 5, "operator": "*"}}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217974224535631038) *****[0m
275
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:36] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

[32m***** Suggested tool call (call_-9217975117889680342): calculator *****[0m
Arguments: 
{"input": {"a": 433, "b": 275, "operator": "+"}}
[32m***********************************************************************[0m

--------------------------------------------------------------------------------
[35m
>>>>>>>> EXECUTING FUNCTION calculator...[0m
[33mUser[0m (to Assistant):

[33mUser[0m (to Assistant):

[32m***** Response from calling tool (call_-9217975117889680342) *****[0m
708
[32m******************************************************************[0m

--------------------------------------------------------------------------------
[31m
>>>>>>>> USING AUTO REPLY...[0m
[autogen.oai.client: 11-25 13:28:37] {351} WARNING - Model GLM-4-Plus is not found. The cost will be 0. In your config_list, add field {"price" : [prompt_price_per_1k, completion_token_price_per_1k]} for customized pricing.
[33mAssistant[0m (to User):

The result is 708. TERMINATE

--------------------------------------------------------------------------------

总结

本教程展示了如何使用 Python 和 autogen 库创建一个简单的计算器工具,并将其集成到对话代理中。通过注册工具函数和发起对话,我们可以轻松地使用计算器工具进行计算。

参考链接:
https://microsoft.github.io/autogen/0.2/docs/tutorial/tool-use#tool-schema
如果有任何问题,欢迎在评论区提问。


原文地址:https://blog.csdn.net/qq_41472205/article/details/144027319

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!