Skip to content

Index

AsyncBaseTool #

Bases: BaseTool

基础级别的工具类,向后兼容旧的工具规范,同时也支持异步。

Source code in llama_index/core/tools/types.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
class AsyncBaseTool(BaseTool):
    """基础级别的工具类,向后兼容旧的工具规范,同时也支持异步。"""

    def __call__(self, *args: Any, **kwargs: Any) -> ToolOutput:
        return self.call(*args, **kwargs)

    @abstractmethod
    def call(self, input: Any) -> ToolOutput:
        """
        这是应该由工具开发人员实现的方法。
        """

    @abstractmethod
    async def acall(self, input: Any) -> ToolOutput:
        """这是call方法的异步版本。
工具开发者也应该实现一个与异步兼容的版本。
"""

call abstractmethod #

call(input: Any) -> ToolOutput

这是应该由工具开发人员实现的方法。

Source code in llama_index/core/tools/types.py
161
162
163
164
165
@abstractmethod
def call(self, input: Any) -> ToolOutput:
    """
    这是应该由工具开发人员实现的方法。
    """

acall abstractmethod async #

acall(input: Any) -> ToolOutput

这是call方法的异步版本。 工具开发者也应该实现一个与异步兼容的版本。

Source code in llama_index/core/tools/types.py
167
168
169
170
171
    @abstractmethod
    async def acall(self, input: Any) -> ToolOutput:
        """这是call方法的异步版本。
工具开发者也应该实现一个与异步兼容的版本。
"""

BaseToolAsyncAdapter #

Bases: AsyncBaseTool

适配器类,允许将同步工具用作异步工具。

Source code in llama_index/core/tools/types.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class BaseToolAsyncAdapter(AsyncBaseTool):
    """适配器类,允许将同步工具用作异步工具。"""

    def __init__(self, tool: BaseTool):
        self.base_tool = tool

    @property
    def metadata(self) -> ToolMetadata:
        return self.base_tool.metadata

    def call(self, input: Any) -> ToolOutput:
        return self.base_tool(input)

    async def acall(self, input: Any) -> ToolOutput:
        return self.call(input)

BaseTool #

Source code in llama_index/core/tools/types.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
class BaseTool:
    @property
    @abstractmethod
    def metadata(self) -> ToolMetadata:
        pass

    @abstractmethod
    def __call__(self, input: Any) -> ToolOutput:
        pass

    def _process_langchain_tool_kwargs(
        self,
        langchain_tool_kwargs: Any,
    ) -> Dict[str, Any]:
        """处理 langchain 工具的 kwargs。"""
        if "name" not in langchain_tool_kwargs:
            langchain_tool_kwargs["name"] = self.metadata.name or ""
        if "description" not in langchain_tool_kwargs:
            langchain_tool_kwargs["description"] = self.metadata.description
        if "fn_schema" not in langchain_tool_kwargs:
            langchain_tool_kwargs["args_schema"] = self.metadata.fn_schema
        return langchain_tool_kwargs

    def to_langchain_tool(
        self,
        **langchain_tool_kwargs: Any,
    ) -> "Tool":
        """到langchain工具。"""
        from llama_index.core.bridge.langchain import Tool

        langchain_tool_kwargs = self._process_langchain_tool_kwargs(
            langchain_tool_kwargs
        )
        return Tool.from_function(
            func=self.__call__,
            **langchain_tool_kwargs,
        )

    def to_langchain_structured_tool(
        self,
        **langchain_tool_kwargs: Any,
    ) -> "StructuredTool":
        """将结构化工具转换为语言链。"""
        from llama_index.core.bridge.langchain import StructuredTool

        langchain_tool_kwargs = self._process_langchain_tool_kwargs(
            langchain_tool_kwargs
        )
        return StructuredTool.from_function(
            func=self.__call__,
            **langchain_tool_kwargs,
        )

to_langchain_tool #

to_langchain_tool(**langchain_tool_kwargs: Any) -> Tool

到langchain工具。

Source code in llama_index/core/tools/types.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def to_langchain_tool(
    self,
    **langchain_tool_kwargs: Any,
) -> "Tool":
    """到langchain工具。"""
    from llama_index.core.bridge.langchain import Tool

    langchain_tool_kwargs = self._process_langchain_tool_kwargs(
        langchain_tool_kwargs
    )
    return Tool.from_function(
        func=self.__call__,
        **langchain_tool_kwargs,
    )

to_langchain_structured_tool #

to_langchain_structured_tool(
    **langchain_tool_kwargs: Any,
) -> StructuredTool

将结构化工具转换为语言链。

Source code in llama_index/core/tools/types.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def to_langchain_structured_tool(
    self,
    **langchain_tool_kwargs: Any,
) -> "StructuredTool":
    """将结构化工具转换为语言链。"""
    from llama_index.core.bridge.langchain import StructuredTool

    langchain_tool_kwargs = self._process_langchain_tool_kwargs(
        langchain_tool_kwargs
    )
    return StructuredTool.from_function(
        func=self.__call__,
        **langchain_tool_kwargs,
    )

ToolMetadata dataclass #

Source code in llama_index/core/tools/types.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@dataclass
class ToolMetadata:
    description: str
    name: Optional[str] = None
    fn_schema: Optional[Type[BaseModel]] = DefaultToolFnSchema
    return_direct: bool = False

    def get_parameters_dict(self) -> dict:
        if self.fn_schema is None:
            parameters = {
                "type": "object",
                "properties": {
                    "input": {"title": "input query string", "type": "string"},
                },
                "required": ["input"],
            }
        else:
            parameters = self.fn_schema.schema()
            parameters = {
                k: v
                for k, v in parameters.items()
                if k in ["type", "properties", "required", "definitions"]
            }
        return parameters

    @property
    def fn_schema_str(self) -> str:
        """获取函数模式作为字符串。"""
        if self.fn_schema is None:
            raise ValueError("fn_schema is None.")
        parameters = self.get_parameters_dict()
        return json.dumps(parameters)

    def get_name(self) -> str:
        """获取名称。"""
        if self.name is None:
            raise ValueError("name is None.")
        return self.name

    @deprecated(
        "Deprecated in favor of `to_openai_tool`, which should be used instead."
    )
    def to_openai_function(self) -> Dict[str, Any]:
        """已弃用并由`to_openai_tool`替代。
应调用的函数的名称和参数,由模型生成。
"""
        return {
            "name": self.name,
            "description": self.description,
            "parameters": self.get_parameters_dict(),
        }

    def to_openai_tool(self, skip_length_check: bool = False) -> Dict[str, Any]:
        """给OpenAI工具。"""
        if not skip_length_check and len(self.description) > 1024:
            raise ValueError(
                "Tool description exceeds maximum length of 1024 characters. "
                "Please shorten your description or move it to the prompt."
            )
        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": self.get_parameters_dict(),
            },
        }

fn_schema_str property #

fn_schema_str: str

获取函数模式作为字符串。

get_name #

get_name() -> str

获取名称。

Source code in llama_index/core/tools/types.py
51
52
53
54
55
def get_name(self) -> str:
    """获取名称。"""
    if self.name is None:
        raise ValueError("name is None.")
    return self.name

to_openai_function #

to_openai_function() -> Dict[str, Any]

已弃用并由to_openai_tool替代。 应调用的函数的名称和参数,由模型生成。

Source code in llama_index/core/tools/types.py
57
58
59
60
61
62
63
64
65
66
67
68
    @deprecated(
        "Deprecated in favor of `to_openai_tool`, which should be used instead."
    )
    def to_openai_function(self) -> Dict[str, Any]:
        """已弃用并由`to_openai_tool`替代。
应调用的函数的名称和参数,由模型生成。
"""
        return {
            "name": self.name,
            "description": self.description,
            "parameters": self.get_parameters_dict(),
        }

to_openai_tool #

to_openai_tool(
    skip_length_check: bool = False,
) -> Dict[str, Any]

给OpenAI工具。

Source code in llama_index/core/tools/types.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
def to_openai_tool(self, skip_length_check: bool = False) -> Dict[str, Any]:
    """给OpenAI工具。"""
    if not skip_length_check and len(self.description) > 1024:
        raise ValueError(
            "Tool description exceeds maximum length of 1024 characters. "
            "Please shorten your description or move it to the prompt."
        )
    return {
        "type": "function",
        "function": {
            "name": self.name,
            "description": self.description,
            "parameters": self.get_parameters_dict(),
        },
    }

ToolOutput #

Bases: BaseModel

工具输出。

Source code in llama_index/core/tools/types.py
87
88
89
90
91
92
93
94
95
96
97
98
class ToolOutput(BaseModel):
    """工具输出。"""

    content: str
    tool_name: str
    raw_input: Dict[str, Any]
    raw_output: Any
    is_error: bool = False

    def __str__(self) -> str:
        """字符串。"""
        return str(self.content)