Ở đây, chúng tôi sẽ sử dụng GoogleSearch như một ví dụ để minh họa cách tích hợp một công cụ một cách nhanh chóng.
1. Chuẩn bị tệp yaml của Nhà cung cấp Công cụ
Giới thiệu
Tệp yaml này khai báo một nhà cung cấp công cụ mới và bao gồm thông tin như tên nhà cung cấp, biểu tượng, tác giả và các chi tiết khác được lấy từ frontend để hiển thị.
Ví dụ
Chúng ta cần tạo một mô-đun google (thư mục) trong core/tools/provider/builtin, và tạo google.yaml. Tên phải phù hợp với tên mô-đun.
Sau đó, tất cả các hoạt động liên quan đến công cụ này sẽ được thực hiện trong mô-đun này.
identity: # Basic information of the tool provider
author: Dify # Author
name: google # Name, unique, no duplication with other providers
label: # Label for frontend display
en_US: Google # English label
zh_Hans: Google # Chinese label
description: # Description for frontend display
en_US: Google # English description
zh_Hans: Google # Chinese description
icon: icon.svg # Icon, needs to be placed in the _assets folder of the current module
Trường identity là bắt buộc, nó chứa thông tin cơ bản của nhà cung cấp công cụ, bao gồm tác giả, tên, nhãn, mô tả, biểu tượng, v.v.
Biểu tượng cần được đặt trong thư mục _assets của mô-đun hiện tại, bạn có thể tham khảo: api/core/tools/provider/builtin/google/_assets/icon.svg
Google, như một công cụ của bên thứ ba, sử dụng API được cung cấp bởi SerpApi, đòi hỏi một Khóa API để sử dụng. Điều này có nghĩa là công cụ này cần một chứng chỉ để sử dụng. Đối với các công cụ như wikipedia, không cần phải điền vào trường chứng chỉ, bạn có thể tham khảo: api/core/tools/provider/builtin/wikipedia/wikipedia.yaml
identity:
author: Dify
name: wikipedia
label:
en_US: Wikipedia
zh_Hans: 维基百科
pt_BR: Wikipedia
description:
en_US: Wikipedia is a free online encyclopedia, created and edited by volunteers around the world.
zh_Hans: 维基百科是一个由全世界的志愿者创建和编辑的免费在线百科全书。
pt_BR: Wikipedia is a free online encyclopedia, created and edited by volunteers around the world.
icon: icon.svg
credentials_for_provider:
Sau khi cấu hình trường chứng chỉ, hiệu ứng như sau:
identity:
author: Dify
name: google
label:
en_US: Google
zh_Hans: Google
description:
en_US: Google
zh_Hans: Google
icon: icon.svg
credentials_for_provider: # Credential field
serpapi_api_key: # Credential field name
type: secret-input # Credential field type
required: true # Required or not
label: # Credential field label
en_US: SerpApi API key # English label
zh_Hans: SerpApi API key # Chinese label
placeholder: # Credential field placeholder
en_US: Please input your SerpApi API key # English placeholder
zh_Hans: 请输入你的 SerpApi API key # Chinese placeholder
help: # Credential field help text
en_US: Get your SerpApi API key from SerpApi # English help text
zh_Hans: 从 SerpApi 获取您的 SerpApi API key # Chinese help text
url: https://serpapi.com/manage-api-key # Credential field help link
type: Loại trường chứng chỉ, hiện tại có thể là secret-input, text-input, hoặc select, tương ứng với hộp nhập mật khẩu, hộp nhập văn bản và hộp thả xuống, tương ứng. Nếu thiết lập thành secret-input, nó sẽ ẩn nội dung nhập trên frontend và backend sẽ mã hóa nội dung nhập.
3. Chuẩn bị Công cụ yaml
Một nhà cung cấp có thể có nhiều công cụ, mỗi công cụ cần một tệp yaml để mô tả, tệp này chứa thông tin cơ bản, tham số, đầu ra, v.v. của công cụ.
Vẫn tiếp tục sử dụng GoogleSearch làm ví dụ, chúng ta cần tạo một mô-đun công cụ trong mô-đun google, và tạo tools/google_search.yaml, nội dung như sau.
identity: # Basic information of the tool
name: google_search # Tool name, unique, no duplication with other tools
author: Dify # Author
label: # Label for frontend display
en_US: GoogleSearch # English label
zh_Hans: 谷歌搜索 # Chinese label
description: # Description for frontend display
human: # Introduction for frontend display, supports multiple languages
en_US: A tool for performing a Google SERP search and extracting snippets and webpages.Input should be a search query.
zh_Hans: 一个用于执行 Google SERP 搜索并提取片段和网页的工具。输入应该是一个搜索查询。
llm: A tool for performing a Google SERP search and extracting snippets and webpages.Input should be a search query. # Introduction passed to LLM, in order to make LLM better understand this tool, we suggest to write as detailed information about this tool as possible here, so that LLM can understand and use this tool
parameters: # Parameter list
- name: query # Parameter name
type: string # Parameter type
required: true # Required or not
label: # Parameter label
en_US: Query string # English label
zh_Hans: 查询语句 # Chinese label
human_description: # Introduction for frontend display, supports multiple languages
en_US: used for searching
zh_Hans: 用于搜索网页内容
llm_description: key words for searching # Introduction passed to LLM, similarly, in order to make LLM better understand this parameter, we suggest to write as detailed information about this parameter as possible here, so that LLM can understand this parameter
form: llm # Form type, llm means this parameter needs to be inferred by Agent, the frontend will not display this parameter
- name: result_type
type: select # Parameter type
required: true
options: # Drop-down box options
- value: text
label:
en_US: text
zh_Hans: 文本
- value: link
label:
en_US: link
zh_Hans: 链接
default: link
label:
en_US: Result type
zh_Hans: 结果类型
human_description:
en_US: used for selecting the result type, text or link
zh_Hans: 用于选择结果类型,使用文本还是链接进行展示
form: form # Form type, form means this parameter needs to be filled in by the user on the frontend before the conversation starts
Trường identitylà bắt buộc, nó chứa thông tin cơ bản của công cụ, bao gồm tên, tác giả, nhãn, mô tả, v.v.
parameters Danh sách tham số
name Tên tham số, duy nhất, không trùng với các tham số khác
type Loại tham số, hiện tại hỗ trợ bốn loại: string, number, boolean, select, tương ứng với văn bản, số, boolean, hộp thả xuống
required Yêu cầu hoặc không
Trong chế độ llm, nếu tham số này là bắt buộc, Agent phải suy luận tham số này
Trong chế độ form, nếu tham số này là bắt buộc, người dùng phải điền vào tham số này trên frontend trước khi cuộc trò chuyện bắt đầu
options Các tùy chọn của tham số
Trong chế độ llm, ChatX sẽ truyền tất cả các tùy chọn này cho LLM, LLM có thể suy luận dựa trên các tùy chọn này
Trong chế độ form, khi type là select, frontend sẽ hiển thị các tùy chọn này
default Giá trị mặc định
label Nhãn tham số, cho việc hiển thị ở frontend
human_description Giới thiệu cho việc hiển thị ở frontend, hỗ trợ nhiều ngôn ngữ
llm_description Giới thiệu được truyền cho LLM, để LLM hiểu rõ hơn về tham số này, chúng tôi đề xuất viết thông tin chi tiết về tham số này càng nhiều càng tốt ở đây, để LLM có thể hiểu và sử dụng tham số này
form Loại biểu mẫu, hiện tại hỗ trợ llm, form hai loại, tương ứng với tự suy luận của Agent và điền trên frontend
4. Thêm Công cụ Logic
Sau khi hoàn thành cấu hình công cụ, chúng ta có thể bắt đầu viết mã công cụ xác định cách gọi nó.
Tạo google_search.py trong mô-đun google/tools, nội dung như sau.
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage
from typing import Any, Dict, List, Union
class GoogleSearchTool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
"""
query = tool_parameters['query']
result_type = tool_parameters['result_type']
api_key = self.runtime.credentials['serpapi_api_key']
# TODO: search with serpapi
result = SerpAPI(api_key).run(query, result_type=result_type)
if result_type == 'text':
return self.create_text_message(text=result)
return self.create_link_message(link=result)
Tham số
Logic tổng thể của công cụ nằm trong phương thức _invoke, phương thức này chấp nhận hai tham số: user_id và tool_parameters, đại diện cho ID người dùng và các tham số công cụ tương ứng
Dữ liệu Trả về
Khi công cụ trả về, bạn có thể chọn trả về một tin nhắn hoặc nhiều tin nhắn, ở đây chúng ta trả về một tin nhắn, sử dụng create_text_message và create_link_message có thể tạo ra một tin nhắn văn bản hoặc một tin nhắn liên kết.
5. Thêm Mã Nhà cung cấp
Cuối cùng, chúng ta cần tạo một lớp nhà cung cấp dưới mô-đun nhà cung cấp để triển khai logic xác minh chứng chỉ của nhà cung cấp. Nếu xác minh chứng chỉ thất bại, nó sẽ ném một ngoại lệ ToolProviderCredentialValidationError.
Tạo google.py trong mô-đun google, nội dung như sau.
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolProviderType
from core.tools.tool.tool import Tool
from core.tools.provider.builtin_tool_provider import BuiltinToolProviderController
from core.tools.errors import ToolProviderCredentialValidationError
from core.tools.provider.builtin.google.tools.google_search import GoogleSearchTool
from typing import Any, Dict
class GoogleProvider(BuiltinToolProviderController):
def _validate_credentials(self, credentials: Dict[str, Any]) -> None:
try:
# 1. Here you need to instantiate a GoogleSearchTool with GoogleSearchTool(), it will automatically load the yaml configuration of GoogleSearchTool, but at this time it does not have credential information inside
# 2. Then you need to use the fork_tool_runtime method to pass the current credential information to GoogleSearchTool
# 3. Finally, invoke it, the parameters need to be passed according to the parameter rules configured in the yaml of GoogleSearchTool
GoogleSearchTool().fork_tool_runtime(
meta={
"credentials": credentials,
}
).invoke(
user_id='',
tool_parameters={
"query": "test",
"result_type": "link"
},
)
except Exception as e:
raise ToolProviderCredentialValidationError(str(e))
Hoàn thành
Sau khi hoàn thành các bước trên, chúng ta có thể thấy công cụ này trên frontend và nó có thể được sử dụng trong Agent.
Tất nhiên, vì google_search cần một chứng chỉ, trước khi sử dụng nó, bạn cũng cần nhập chứng chỉ của mình trên frontend.