将 Enum 作为工具传递给客户端:“TypeError:ModelMetaclass 类型的对象不可 JSON 序列化”

问题描述 投票:0回答:1

我正在尝试调用langchain中的工具。

该函数接受

IntEnum
输入。它掷骰子并返回一个随机整数。

import random
from enum import IntEnum

from dotenv import load_dotenv
from langchain.tools import Tool, tool
from langchain_openai import AzureChatOpenAI
from pydantic import BaseModel, Field

load_dotenv()


class Dice(IntEnum):
    """
    Roll a D&D dice. A d4 dice has 4 sides and thus
    rolling a d4 dice will return a value from 1 through 4.
    """

    d4 = 4
    d6 = 6
    d8 = 8
    d10 = 10
    d12 = 12
    d20 = 20
    d100 = 100


def roll_dice(dice: Dice) -> int:
    """
    Simulates rolling a dice with a specified number of sides.

    Parameters:
    dice (Dice): A dice to roll.

    Returns:
    int: The result of the dice roll.
    """
    return random.randint(1, dice.value)


class RollDiceInput(BaseModel):
    dice: Dice


def get_function_description(func):
    """Extract docstrings from the functions"""
    return func.__doc__.strip()


# Define the tool with the input schema
roll_dice_tool = Tool(
    name="roll_dice",
    description=get_function_description(roll_dice),
    args_schema=RollDiceInput,
    func=roll_dice,
)

# Define the prompt
prompt = """
Roll a dice in Dungeons and Dragons.
"""

client = AzureChatOpenAI()

# Call the GPT-4 API with descriptions extracted from docstrings
response = client.invoke(
    model="gpt-4o",
    input=prompt,
    tools=[roll_dice_tool],
    tool_choice={
        "type": "function",
        "function": {"name": "roll_dice"},
    },  # forces the model to call the `roll_dice` function
)

它产生错误:

TypeError: Object of type ModelMetaclass is not JSON serializable
.

序列化该函数似乎失败。

如何正确传递和定义

roll_dice
函数的工具?

郎链0.3.0 langchain-openai 0.2.0

python pydantic langchain py-langchain
1个回答
0
投票

您必须将工具绑定到 llm 模型。这将创建一个可以调用工具的可运行程序。然后使用输入提示调用该对象。此外,模型名称必须在聊天模型定义中传递。

client = AzureChatOpenAI(model="gpt-4o")

client_with_tool = client.bind_tools(     # <--- bind the tool here
    tools=[roll_dice_tool],
    tool_choice={
        "type": "function",
        "function": {"name": "roll_dice"},
    },  # forces the model to call the `roll_dice` function
)
response = client_with_tool.invoke(       # <--- invoke the client with the bound tools
    input=prompt,
)
© www.soinside.com 2019 - 2024. All rights reserved.