跳至内容

索引

AsyncBaseTool #

基础类: BaseTool

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

Source code in llama-index-core/llama_index/core/tools/types.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
class AsyncBaseTool(BaseTool):
    """
    Base-level tool class that is backwards compatible with the old tool spec but also
    supports async.
    """

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

    @abstractmethod
    def call(self, input: Any) -> ToolOutput:
        """
        This is the method that should be implemented by the tool developer.
        """

    @abstractmethod
    async def acall(self, input: Any) -> ToolOutput:
        """
        This is the async version of the call method.
        Should also be implemented by the tool developer as an
        async-compatible implementation.
        """

调用 abstractmethod #

call(input: Any) -> ToolOutput

这是工具开发者应该实现的方法。

Source code in llama-index-core/llama_index/core/tools/types.py
176
177
178
179
180
@abstractmethod
def call(self, input: Any) -> ToolOutput:
    """
    This is the method that should be implemented by the tool developer.
    """

acall abstractmethod async #

acall(input: Any) -> ToolOutput

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

Source code in llama-index-core/llama_index/core/tools/types.py
182
183
184
185
186
187
188
@abstractmethod
async def acall(self, input: Any) -> ToolOutput:
    """
    This is the async version of the call method.
    Should also be implemented by the tool developer as an
    async-compatible implementation.
    """

BaseToolAsyncAdapter #

基础类: AsyncBaseTool

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

Source code in llama-index-core/llama_index/core/tools/types.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class BaseToolAsyncAdapter(AsyncBaseTool):
    """
    Adapter class that allows a synchronous tool to be used as an async tool.
    """

    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 await asyncio.to_thread(self.call, input)

基础工具 #

基类: DispatcherSpanMixin

Source code in llama-index-core/llama_index/core/tools/types.py
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
153
154
155
156
157
158
159
160
161
162
163
164
class BaseTool(DispatcherSpanMixin):
    @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]:
        """Process langchain tool 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

        # Callback dont exist on langchain
        if "_callback" in langchain_tool_kwargs:
            del langchain_tool_kwargs["_callback"]
        if "_async_callback" in langchain_tool_kwargs:
            del langchain_tool_kwargs["_async_callback"]

        return langchain_tool_kwargs

    def to_langchain_tool(
        self,
        **langchain_tool_kwargs: Any,
    ) -> "Tool":
        """To langchain tool."""
        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":
        """To langchain structured tool."""
        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/llama_index/core/tools/types.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def to_langchain_tool(
    self,
    **langchain_tool_kwargs: Any,
) -> "Tool":
    """To langchain tool."""
    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

转换为langchain结构化工具。

Source code in llama-index-core/llama_index/core/tools/types.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def to_langchain_structured_tool(
    self,
    **langchain_tool_kwargs: Any,
) -> "StructuredTool":
    """To langchain structured tool."""
    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,
    )

工具元数据 dataclass #

工具元数据(描述: 字符串, 名称: 可选[字符串] = 无, 函数模式: 可选[类型[pydantic.main.基础模型]] = <类>, 直接返回: 布尔值 = 假)

参数:

名称 类型 描述 默认值
description str
required
name str | None
None
fn_schema Type[BaseModel] | None
<class 'llama_index.core.tools.types.DefaultToolFnSchema'>
return_direct bool
False
Source code in llama-index-core/llama_index/core/tools/types.py
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
85
86
87
88
89
@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.model_json_schema()
            parameters = {
                k: v
                for k, v in parameters.items()
                if k in ["type", "properties", "required", "definitions", "$defs"]
            }
        return parameters

    @property
    def fn_schema_str(self) -> str:
        """Get fn schema as string."""
        if self.fn_schema is None:
            raise ValueError("fn_schema is None.")
        parameters = self.get_parameters_dict()
        return json.dumps(parameters, ensure_ascii=False)

    def get_name(self) -> str:
        """Get name."""
        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]:
        """
        Deprecated and replaced by `to_openai_tool`.
        The name and arguments of a function that should be called, as generated by the
        model.
        """
        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]:
        """To OpenAI tool."""
        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/llama_index/core/tools/types.py
54
55
56
57
58
def get_name(self) -> str:
    """Get name."""
    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/llama_index/core/tools/types.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@deprecated(
    "Deprecated in favor of `to_openai_tool`, which should be used instead."
)
def to_openai_function(self) -> Dict[str, Any]:
    """
    Deprecated and replaced by `to_openai_tool`.
    The name and arguments of a function that should be called, as generated by the
    model.
    """
    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/llama_index/core/tools/types.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def to_openai_tool(self, skip_length_check: bool = False) -> Dict[str, Any]:
    """To OpenAI tool."""
    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(),
        },
    }

工具输出 #

基类: BaseModel

工具输出。

参数:

名称 类型 描述 默认值
content str
required
tool_name str
required
raw_input Dict[str, Any]
required
raw_output Any
required
is_error bool
False
Source code in llama-index-core/llama_index/core/tools/types.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
class ToolOutput(BaseModel):
    """Tool output."""

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

    def __str__(self) -> str:
        """String."""
        return str(self.content)