Skip to content

Commit

Permalink
FEAT: Add Brave Search and Trello(12 Tools) Included (#3040)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yash-1511 authored Apr 1, 2024
1 parent 84d118d commit 1322696
Show file tree
Hide file tree
Showing 34 changed files with 1,497 additions and 0 deletions.
1 change: 1 addition & 0 deletions api/core/tools/provider/builtin/brave/_assets/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
22 changes: 22 additions & 0 deletions api/core/tools/provider/builtin/brave/brave.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from typing import Any

from core.tools.errors import ToolProviderCredentialValidationError
from core.tools.provider.builtin.brave.tools.brave_search import BraveSearchTool
from core.tools.provider.builtin_tool_provider import BuiltinToolProviderController


class BraveProvider(BuiltinToolProviderController):
def _validate_credentials(self, credentials: dict[str, Any]) -> None:
try:
BraveSearchTool().fork_tool_runtime(
meta={
"credentials": credentials,
}
).invoke(
user_id='',
tool_parameters={
"query": "Sachin Tendulkar",
},
)
except Exception as e:
raise ToolProviderCredentialValidationError(str(e))
29 changes: 29 additions & 0 deletions api/core/tools/provider/builtin/brave/brave.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
identity:
author: Yash Parmar
name: brave
label:
en_US: Brave
zh_Hans: Brave
pt_BR: Brave
description:
en_US: Brave
zh_Hans: Brave
pt_BR: Brave
icon: icon.svg
credentials_for_provider:
brave_search_api_key:
type: secret-input
required: true
label:
en_US: Brave Search API key
zh_Hans: Brave Search API key
pt_BR: Brave Search API key
placeholder:
en_US: Please input your Brave Search API key
zh_Hans: 请输入你的 Brave Search API key
pt_BR: Please input your Brave Search API key
help:
en_US: Get your Brave Search API key from Brave
zh_Hans: 从 Brave 获取您的 Brave Search API key
pt_BR: Get your Brave Search API key from Brave
url: https://brave.com/search/api/
40 changes: 40 additions & 0 deletions api/core/tools/provider/builtin/brave/tools/brave_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from typing import Any

from langchain.tools import BraveSearch

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool


class BraveSearchTool(BuiltinTool):
"""
Tool for performing a search using Brave search engine.
"""

def _invoke(self, user_id: str, tool_parameters: dict[str, Any]) -> ToolInvokeMessage | list[ToolInvokeMessage]:
"""
Invoke the Brave search tool.
Args:
user_id (str): The ID of the user invoking the tool.
tool_parameters (dict[str, Any]): The parameters for the tool invocation.
Returns:
ToolInvokeMessage | list[ToolInvokeMessage]: The result of the tool invocation.
"""
query = tool_parameters.get('query', '')
count = tool_parameters.get('count', 3)
api_key = self.runtime.credentials['brave_search_api_key']

if not query:
return self.create_text_message('Please input query')

tool = BraveSearch.from_api_key(api_key=api_key, search_kwargs={"count": count})

results = tool.run(query)

if not results:
return self.create_text_message(f"No results found for '{query}' in Tavily")
else:
return self.create_text_message(text=results)

41 changes: 41 additions & 0 deletions api/core/tools/provider/builtin/brave/tools/brave_search.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
identity:
name: brave_search
author: Yash Parmar
label:
en_US: BraveSearch
zh_Hans: BraveSearch
pt_BR: BraveSearch
description:
human:
en_US: BraveSearch is a privacy-focused search engine that leverages its own index to deliver unbiased, independent, and fast search results. It's designed to respect user privacy by not tracking searches or personal information, making it a secure choice for those concerned about online privacy.
zh_Hans: BraveSearch 是一个注重隐私的搜索引擎,它利用自己的索引来提供公正、独立和快速的搜索结果。它旨在通过不跟踪搜索或个人信息来尊重用户隐私,为那些关注在线隐私的用户提供了一个安全的选择。
pt_BR: BraveSearch é um mecanismo de busca focado na privacidade que utiliza seu próprio índice para entregar resultados de busca imparciais, independentes e rápidos. Ele é projetado para respeitar a privacidade do usuário, não rastreando buscas ou informações pessoais, tornando-se uma escolha segura para aqueles preocupados com a privacidade online.
llm: BraveSearch is a privacy-centric search engine utilizing its unique index to offer unbiased, independent, and swift search results. It aims to protect user privacy by avoiding the tracking of search activities or personal data, presenting a secure option for users mindful of their online privacy.
parameters:
- name: query
type: string
required: true
label:
en_US: Query string
zh_Hans: 查询语句
pt_BR: Query string
human_description:
en_US: The text input used for initiating searches on the web, focusing on delivering relevant and accurate results without compromising user privacy.
zh_Hans: 用于在网上启动搜索的文本输入,专注于提供相关且准确的结果,同时不妨碍用户隐私。
pt_BR: A entrada de texto usada para iniciar pesquisas na web, focada em entregar resultados relevantes e precisos sem comprometer a privacidade do usuário.
llm_description: Keywords or phrases entered to perform searches, aimed at providing relevant and precise results while ensuring the privacy of the user is maintained.
form: llm
- name: count
type: number
required: false
default: 3
label:
en_US: Result count
zh_Hans: 结果数量
pt_BR: Contagem de resultados
human_description:
en_US: The number of search results to return, allowing users to control the breadth of their search output.
zh_Hans: 要返回的搜索结果数量,允许用户控制他们搜索输出的广度。
pt_BR: O número de resultados de pesquisa a serem retornados, permitindo que os usuários controlem a amplitude de sua saída de pesquisa.
llm_description: Specifies the amount of search results to be displayed, offering users the ability to adjust the scope of their search findings.
form: llm
1 change: 1 addition & 0 deletions api/core/tools/provider/builtin/trello/_assets/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
47 changes: 47 additions & 0 deletions api/core/tools/provider/builtin/trello/tools/create_board.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
from typing import Union

import requests

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool


class CreateBoardTool(BuiltinTool):
"""
Tool for creating a new Trello board.
"""

def _invoke(self, user_id: str, tool_parameters: dict[str, Union[str, int, bool]]) -> ToolInvokeMessage:
"""
Invoke the tool to create a new Trello board.
Args:
user_id (str): The ID of the user invoking the tool.
tool_parameters (dict[str, Union[str, int, bool]]): The parameters for the tool invocation.
Returns:
ToolInvokeMessage: The result of the tool invocation.
"""
api_key = self.runtime.credentials.get('trello_api_key')
token = self.runtime.credentials.get('trello_api_token')
board_name = tool_parameters.get('name')

if not (api_key and token and board_name):
return self.create_text_message("Missing required parameters: API key, token, or board name.")

url = "https://api.trello.com/1/boards/"
query_params = {
'name': board_name,
'key': api_key,
'token': token
}

try:
response = requests.post(url, params=query_params)
response.raise_for_status()
except requests.exceptions.RequestException as e:
return self.create_text_message("Failed to create board")

board = response.json()
return self.create_text_message(text=f"Board created successfully! Board name: {board['name']}, ID: {board['id']}")

27 changes: 27 additions & 0 deletions api/core/tools/provider/builtin/trello/tools/create_board.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
identity:
name: create_board
author: Yash Parmar
label:
en_US: Create Board
zh_Hans: 创建看板
pt_BR: Criar Quadro
description:
human:
en_US: Creates a new Trello board with a specified name. This tool allows users to quickly add new boards to their Trello account, facilitating project organization and management.
zh_Hans: 使用指定的名称创建一个新的 Trello 看板。此工具允许用户快速向其 Trello 账户添加新的看板,促进项目组织和管理。
pt_BR: Cria um novo quadro Trello com um nome especificado. Esta ferramenta permite que os usuários adicionem rapidamente novos quadros à sua conta Trello, facilitando a organização e gestão de projetos.
llm: Create a new Trello board using the specified name. This functionality simplifies the addition of boards, enhancing project organization and management within Trello.
parameters:
- name: name
type: string
required: true
label:
en_US: Board Name
zh_Hans: 看板名称
pt_BR: Nome do Quadro
human_description:
en_US: The name for the new Trello board. This name helps in identifying and organizing your projects on Trello.
zh_Hans: 新 Trello 看板的名称。这个名称有助于在 Trello 上识别和组织您的项目。
pt_BR: O nome para o novo quadro Trello. Este nome ajuda a identificar e organizar seus projetos no Trello.
llm_description: Specify the name for your new Trello board, aiding in project identification and organization within Trello.
form: llm
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from typing import Union

import requests

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool


class CreateListOnBoardTool(BuiltinTool):
"""
Tool for creating a list on a Trello board by its ID.
"""

def _invoke(self, user_id: str, tool_parameters: dict[str, Union[str, int, bool]]) -> ToolInvokeMessage:
"""
Invoke the tool to create a list on a Trello board by its ID.
Args:
user_id (str): The ID of the user invoking the tool.
tool_parameters (dict[str, Union[str, int, bool]]): The parameters for the tool invocation, including the board ID and list name.
Returns:
ToolInvokeMessage: The result of the tool invocation.
"""
api_key = self.runtime.credentials.get('trello_api_key')
token = self.runtime.credentials.get('trello_api_token')
board_id = tool_parameters.get('id')
list_name = tool_parameters.get('name')

if not (api_key and token and board_id and list_name):
return self.create_text_message("Missing required parameters: API key, token, board ID, or list name.")

url = f"https://api.trello.com/1/boards/{board_id}/lists"
params = {
'name': list_name,
'key': api_key,
'token': token
}

try:
response = requests.post(url, params=params)
response.raise_for_status()
except requests.exceptions.RequestException as e:
return self.create_text_message("Failed to create list")

new_list = response.json()
return self.create_text_message(text=f"List '{new_list['name']}' created successfully with Id {new_list['id']} on board {board_id}.")

Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
identity:
name: create_list_on_board
author: Yash Parmar
label:
en_US: Create List on Board
zh_Hans: 在看板上创建列表
pt_BR: Criar Lista no Quadro
description:
human:
en_US: Creates a new list on a specified Trello board by providing the board's ID and the desired name for the list. Streamlines the process of organizing board content.
zh_Hans: 通过提供看板的 ID 和列表的所需名称,在指定的 Trello 看板上创建一个新列表。简化了组织看板内容的过程。
pt_BR: Cria uma nova lista em um quadro Trello especificado, fornecendo o ID do quadro e o nome desejado para a lista. Facilita o processo de organização do conteúdo do quadro.
llm: Generate a new list within a Trello board by specifying the board's ID and a name for the list. Enhances board management by allowing quick additions of new lists.
parameters:
- name: id
type: string
required: true
label:
en_US: Board ID
zh_Hans: 看板 ID
pt_BR: ID do Quadro
human_description:
en_US: The unique identifier of the Trello board where the new list will be created.
zh_Hans: 新列表将被创建在其上的 Trello 看板的唯一标识符。
pt_BR: O identificador único do quadro Trello onde a nova lista será criada.
llm_description: Input the ID of the Trello board to pinpoint where the new list should be added, ensuring correct placement.
form: llm
- name: name
type: string
required: true
label:
en_US: List Name
zh_Hans: 列表名称
pt_BR: Nome da Lista
human_description:
en_US: The name for the new list to be created on the Trello board.
zh_Hans: 将在 Trello 看板上创建的新列表的名称。
pt_BR: O nome para a nova lista que será criada no quadro Trello.
llm_description: Provide a name for the new list, defining its purpose or content focus, to facilitate board organization.
form: llm
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from typing import Union

import requests

from core.tools.entities.tool_entities import ToolInvokeMessage
from core.tools.tool.builtin_tool import BuiltinTool


class CreateNewCardOnBoardTool(BuiltinTool):
"""
Tool for creating a new card on a Trello board.
"""

def _invoke(self, user_id: str, tool_parameters: dict[str, Union[str, int, bool, None]]) -> ToolInvokeMessage:
"""
Invoke the tool to create a new card on a Trello board.
Args:
user_id (str): The ID of the user invoking the tool.
tool_parameters (dict[str, Union[str, int, bool, None]]): The parameters for the tool invocation, including details for the new card.
Returns:
ToolInvokeMessage: The result of the tool invocation.
"""
api_key = self.runtime.credentials.get('trello_api_key')
token = self.runtime.credentials.get('trello_api_token')

# Ensure required parameters are present
if 'name' not in tool_parameters or 'idList' not in tool_parameters:
return self.create_text_message("Missing required parameters: name or idList.")

url = "https://api.trello.com/1/cards"
params = {**tool_parameters, 'key': api_key, 'token': token}

try:
response = requests.post(url, params=params)
response.raise_for_status()
new_card = response.json()
except requests.exceptions.RequestException as e:
return self.create_text_message("Failed to create card")

return self.create_text_message(text=f"New card '{new_card['name']}' created successfully with ID {new_card['id']}.")

Loading

0 comments on commit 1322696

Please sign in to comment.