Skip to main content
Open In Colab在 GitHub 上打开

如何使用内置工具和工具包

先决条件

本指南假定您熟悉以下概念:

工具

LangChain 拥有大量第三方工具。请访问工具集成以获取可用工具的列表。

重要

使用第三方工具时,请确保您了解该工具的工作原理和权限 它确实如此。阅读其文档并检查是否需要您提供任何服务 从安全的角度来看。有关更多信息,请参阅我们的安全指南。

让我们尝试一下 Wikipedia 集成

!pip install -qU langchain-community wikipedia
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper

api_wrapper = WikipediaAPIWrapper(top_k_results=1, doc_content_chars_max=100)
tool = WikipediaQueryRun(api_wrapper=api_wrapper)

print(tool.invoke({"query": "langchain"}))
Page: LangChain
Summary: LangChain is a framework designed to simplify the creation of applications

该工具具有以下与之关联的默认值:

print(f"Name: {tool.name}")
print(f"Description: {tool.description}")
print(f"args schema: {tool.args}")
print(f"returns directly?: {tool.return_direct}")
Name: wikipedia
Description: A wrapper around Wikipedia. Useful for when you need to answer general questions about people, places, companies, facts, historical events, or other subjects. Input should be a search query.
args schema: {'query': {'description': 'query to look up on wikipedia', 'title': 'Query', 'type': 'string'}}
returns directly?: False

自定义默认工具

我们还可以修改参数的内置名称、描述和 JSON 架构。

在定义参数的 JSON 架构时,输入必须与函数保持一致,因此您不应更改它。但是,您可以轻松地为每个输入定义自定义描述。

from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
from pydantic import BaseModel, Field


class WikiInputs(BaseModel):
"""Inputs to the wikipedia tool."""

query: str = Field(
description="query to look up in Wikipedia, should be 3 or less words"
)


tool = WikipediaQueryRun(
name="wiki-tool",
description="look up things in wikipedia",
args_schema=WikiInputs,
api_wrapper=api_wrapper,
return_direct=True,
)

print(tool.run("langchain"))
Page: LangChain
Summary: LangChain is a framework designed to simplify the creation of applications
print(f"Name: {tool.name}")
print(f"Description: {tool.description}")
print(f"args schema: {tool.args}")
print(f"returns directly?: {tool.return_direct}")
Name: wiki-tool
Description: look up things in wikipedia
args schema: {'query': {'description': 'query to look up in Wikipedia, should be 3 or less words', 'title': 'Query', 'type': 'string'}}
returns directly?: True

如何使用内置工具包

工具包是旨在一起用于特定任务的工具集合。他们有方便的加载方法。

所有 Toolkit 都公开了get_tools方法返回工具列表。

您通常应该以这种方式使用它们:

# Initialize a toolkit
toolkit = ExampleTookit(...)

# Get list of tools
tools = toolkit.get_tools()