如何使用內建工具與工具組
先決條件
本指南假設您熟悉以下概念
工具
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"}))
API 參考:WikipediaQueryRun | WikipediaAPIWrapper
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 Schema。
在定義參數的 JSON Schema 時,重要的是輸入保持與函數相同,因此您不應更改它。但是您可以輕鬆地為每個輸入定義自訂描述。
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"))
API 參考:WikipediaQueryRun | WikipediaAPIWrapper
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
如何使用內建工具組
工具組是設計用於一起完成特定任務的工具集合。它們具有方便的載入方法。
所有工具組都公開一個 get_tools
方法,該方法返回工具列表。
您通常應該這樣使用它們
# Initialize a toolkit
toolkit = ExampleTookit(...)
# Get list of tools
tools = toolkit.get_tools()