Преглед изворни кода

Add custom tools (#2292)

Co-authored-by: luowei <glpat-EjySCyNjWiLqAED-YmwM>
Co-authored-by: crazywoola <427733928@qq.com>
Co-authored-by: crazywoola <100913391+crazywoola@users.noreply.github.com>
Charlie.Wei пре 1 година
родитељ
комит
d2797abdb4

+ 1 - 1
api/core/tools/provider/builtin/gaode/gaode.yaml

@@ -1,5 +1,5 @@
 identity:
 identity:
-  author: CharlirWei
+  author: CharlieWei
   name: gaode
   name: gaode
   label:
   label:
     en_US: Autonavi
     en_US: Autonavi

+ 1 - 1
api/core/tools/provider/builtin/github/github.yaml

@@ -1,5 +1,5 @@
 identity:
 identity:
-  author: CharlirWei
+  author: CharlieWei
   name: github
   name: github
   label:
   label:
     en_US: Github
     en_US: Github

+ 61 - 0
api/core/tools/provider/builtin/github/tools/github_repositories.py

@@ -0,0 +1,61 @@
+import json
+import requests
+from datetime import datetime
+from urllib.parse import quote
+from core.tools.tool.builtin_tool import BuiltinTool
+from core.tools.entities.tool_entities import ToolInvokeMessage
+
+from typing import Any, Dict, List, Union
+
+
+class GihubRepositoriesTool(BuiltinTool):
+    def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
+        """
+            invoke tools
+        """
+        top_n = tool_paramters.get('top_n', 5)
+        query = tool_paramters.get('query', '')
+        if not query:
+            return self.create_text_message('Please input symbol')
+
+        if 'access_tokens' not in self.runtime.credentials or not self.runtime.credentials.get('access_tokens'):
+            return self.create_text_message("Github API Access Tokens is required.")
+        if 'api_version' not in self.runtime.credentials or not self.runtime.credentials.get('api_version'):
+            api_version = '2022-11-28'
+        else:
+            api_version = self.runtime.credentials.get('api_version')
+
+        try:
+            headers = {
+                "Content-Type": "application/vnd.github+json",
+                "Authorization": f"Bearer {self.runtime.credentials.get('access_tokens')}",
+                "X-GitHub-Api-Version": api_version
+            }
+            s = requests.session()
+            api_domain = 'https://api.github.com'
+            response = s.request(method='GET', headers=headers,
+                                 url=f"{api_domain}/search/repositories?"
+                                     f"q={quote(query)}&sort=stars&per_page={top_n}&order=desc")
+            response_data = response.json()
+            if response.status_code == 200 and isinstance(response_data.get('items'), list):
+                contents = list()
+                if len(response_data.get('items')) > 0:
+                    for item in response_data.get('items'):
+                        content = dict()
+                        updated_at_object = datetime.strptime(item['updated_at'], "%Y-%m-%dT%H:%M:%SZ")
+                        content['owner'] = item['owner']['login']
+                        content['name'] = item['name']
+                        content['description'] = item['description'][:100] + '...' if len(item['description']) > 100 else item['description']
+                        content['url'] = item['html_url']
+                        content['star'] = item['watchers']
+                        content['forks'] = item['forks']
+                        content['updated'] = updated_at_object.strftime("%Y-%m-%d")
+                        contents.append(content)
+                    s.close()
+                    return self.create_text_message(self.summary(user_id=user_id, content=json.dumps(contents, ensure_ascii=False)))
+                else:
+                    return self.create_text_message(f'No items related to {query} were found.')
+            else:
+                return self.create_text_message((response.json()).get('message'))
+        except Exception as e:
+            return self.create_text_message("Github API Key and Api Version is invalid. {}".format(e))

+ 42 - 0
api/core/tools/provider/builtin/github/tools/github_repositories.yaml

@@ -0,0 +1,42 @@
+identity:
+  name: github_repositories
+  author: CharlieWei
+  label:
+    en_US: Search Repositories
+    zh_Hans: 仓库搜索
+    pt_BR: Pesquisar Repositórios
+  icon: icon.svg
+description:
+  human:
+    en_US: Search the Github repository to retrieve the open source projects you need
+    zh_Hans: 搜索Github仓库,检索你需要的开源项目。
+    pt_BR: Pesquise o repositório do Github para recuperar os projetos de código aberto necessários.
+  llm: A tool when you wants to search for popular warehouses or open source projects for any keyword. format query condition like "keywords+language:js", language can be other dev languages.
+parameters:
+  - name: query
+    type: string
+    required: true
+    label:
+      en_US: query
+      zh_Hans: 关键字
+      pt_BR: consulta
+    human_description:
+      en_US: You want to find the project development language, keywords, For example. Find 10 Python developed PDF document parsing projects.
+      zh_Hans: 你想要找的项目开发语言、关键字,如:找10个Python开发的PDF文档解析项目。
+      pt_BR: Você deseja encontrar a linguagem de desenvolvimento do projeto, palavras-chave, Por exemplo. Encontre 10 projetos de análise de documentos PDF desenvolvidos em Python.
+    llm_description: The query of you want to search, format query condition like "keywords+language:js", language can be other dev languages, por exemplo. Procuro um projeto de análise de documentos PDF desenvolvido em Python.
+    form: llm
+  - name: top_n
+    type: number
+    default: 5
+    required: true
+    label:
+      en_US: Top N
+      zh_Hans: Top N
+      pt_BR: Topo N
+    human_description:
+      en_US: Number of records returned by sorting based on stars. 5 is returned by default.
+      zh_Hans: 基于stars排序返回的记录数, 默认返回5条。
+      pt_BR: Número de registros retornados por classificação com base em estrelas. 5 é retornado por padrão.
+    llm_description: Extract the first N records from the returned result.
+    form: llm