Compare commits

...

3 Commits

Author SHA1 Message Date
Sam Pink
18e31de2c4 Add-github-api-utility (#3598)
This PR introduces a new GitHub API Wrapper using the requests library.
The new GitHubAPIWrapper class allows users to fetch repository
information for a specified GitHub user. The PR includes the following
changes:

Create a new GitHubAPIWrapper class that provides easy access to the
GitHub API
Add a root validator to ensure the GitHub API key is present in the
environment
Implement _format_repo_info method to format repository information into
a readable string
Add run method to fetch and display repositories for a given user
Update requirements.txt to include requests library
With the new GitHub API Wrapper, users can now easily retrieve
repository information for any GitHub user. This functionality can be
useful for a variety of purposes, such as displaying user profiles,
generating reports, or analyzing repositories for various metrics.

Please let me know if you have any questions or concerns. I look forward
to your feedback and merging this feature into the main branch.
2023-04-30 16:17:53 -07:00
vowelparrot
036510f7e4 Update imports 2023-04-30 16:15:56 -07:00
vowelparrot
7a504b3b3a Fix type 2023-04-30 16:08:53 -07:00
13 changed files with 172 additions and 25 deletions

View File

@@ -27,6 +27,13 @@ from langchain.tools.playwright import (
from langchain.tools.plugin import AIPluginTool
from langchain.tools.scenexplain.tool import SceneXplainTool
from langchain.tools.shell.tool import ShellTool
from langchain.tools.vectorstore.tool import (
VectorStoreQATool,
VectorStoreQAWithSourcesTool,
)
from langchain.tools.wikipedia.tool import WikipediaQueryRun
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
from langchain.tools.zapier.tool import ZapierNLAListActions, ZapierNLARunAction
__all__ = [
"AIPluginTool",
@@ -60,4 +67,10 @@ __all__ = [
"WriteFileTool",
"BaseTool",
"SceneXplainTool",
"VectorStoreQAWithSourcesTool",
"VectorStoreQATool",
"WikipediaQueryRun",
"WolframAlphaQueryRun",
"ZapierNLARunAction",
"ZapierNLAListActions",
]

View File

@@ -1 +1,5 @@
"""Bing Search API toolkit."""
from langchain.tools.bing_search.tool import BingSearchResults, BingSearchRun
__all__ = ["BingSearchRun", "BingSearchResults"]

View File

@@ -0,0 +1 @@
""" GitHub API wrapper toolkit. """

View File

@@ -0,0 +1,29 @@
"""Tool for the GitHub API."""
from langchain.tools.base import BaseTool
from langchain.utilities import GitHubAPIWrapper
class GitHubRepoQueryRun(BaseTool):
"""Tool that adds the capability to query using the GitHub API."""
api_wrapper: GitHubAPIWrapper
name = "GitHub"
description = (
"A wrapper around GitHub API. "
"Useful for fetching repository information for a specified user. "
"Input should be a GitHub username (e.g. 'octocat')."
)
def __init__(self) -> None:
self.api_wrapper = GitHubAPIWrapper()
return
def _run(self, user: str) -> str:
"""Use the GitHub tool."""
return self.api_wrapper.run(user)
async def _arun(self, user: str) -> str:
"""Use the GitHub tool asynchronously."""
raise NotImplementedError("GitHubRepoQueryRun does not support async")

View File

@@ -1 +1,5 @@
"""Google Places API Toolkit."""
from langchain.tools.google_places.tool import GooglePlacesTool
__all__ = ["GooglePlacesTool"]

View File

@@ -1 +1,5 @@
"""Google Search API Toolkit."""
from langchain.tools.google_search.tool import GoogleSearchResults, GoogleSearchRun
__all__ = ["GoogleSearchRun", "GoogleSearchResults"]

View File

@@ -1 +1,5 @@
"""Tool for asking for human input."""
from langchain.tools.human.tool import HumanInputRun
__all__ = ["HumanInputRun"]

View File

@@ -1,32 +1,17 @@
"""Tools for interacting with the user."""
from typing import Optional
import warnings
from typing import Any
from langchain.callbacks.manager import (
AsyncCallbackManagerForToolRun,
RunManager,
)
from langchain.tools.base import BaseTool
from langchain.tools.human.tool import HumanInputRun
class StdInInquireTool(BaseTool):
def StdInInquireTool(*args: Any, **kwargs: Any) -> HumanInputRun:
"""Tool for asking the user for input."""
name: str = "Inquire"
description: str = (
"useful if you do not have enough information to"
" effectively use other tools. Input is best as a clarifying"
" question (to disambiguate) or a request for more context."
warnings.warn(
"StdInInquireTool will be deprecated in the future. "
"Please use HumanInputRun instead.",
DeprecationWarning,
)
def _run(self, prompt: str, run_manager: Optional[RunManager] = None) -> str:
"""Prompt the user for more input."""
return input(f"\n{prompt}")
async def _arun(
self,
query: str,
run_manager: Optional[AsyncCallbackManagerForToolRun] = None,
) -> str:
raise NotImplementedError(f"{self.__class__.__name__} does not support async")
return HumanInputRun(*args, **kwargs)

View File

@@ -1 +1,8 @@
"""Wolfram Alpha API toolkit."""
from langchain.tools.wolfram_alpha.tool import WolframAlphaQueryRun
__all__ = [
"WolframAlphaQueryRun",
]

View File

@@ -1 +1,8 @@
"""Zapier Tool."""
from langchain.tools.zapier.tool import ZapierNLAListActions, ZapierNLARunAction
__all__ = [
"ZapierNLARunAction",
"ZapierNLAListActions",
]

View File

@@ -15,6 +15,7 @@ from langchain.utilities.searx_search import SearxSearchWrapper
from langchain.utilities.serpapi import SerpAPIWrapper
from langchain.utilities.wikipedia import WikipediaAPIWrapper
from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapper
from langchain.utilities.github import GitHubAPIWrapper
__all__ = [
"ApifyWrapper",
@@ -33,4 +34,5 @@ __all__ = [
"PythonREPL",
"LambdaWrapper",
"PowerBIDataset",
"GitHubAPIWrapper",
]

View File

@@ -0,0 +1,86 @@
"""Util that calls GitHub API using requests."""
from typing import Any, Dict, Optional
import requests
from pydantic import Extra, root_validator
from langchain.tools.base import BaseModel
from langchain.utils import get_from_dict_or_env
"""
Example usage
from langchain.utilities import GitHubAPIWrapper
#set env variable GITHUB_API_KEY
import os
os.environ['GITHUB_API_KEY'] = ''
github_api = GitHubAPIWrapper()
print(github_api.run('SamPink'))
"""
class GitHubAPIWrapper(BaseModel):
"""Wrapper for GitHub API using requests.
Docs for using:
1. Go to GitHub and sign up for an API key
2. Save your API KEY into GITHUB_API_KEY env variable
3. pip install requests
"""
github_api_key: Optional[str] = None
class Config:
"""Configuration for this pydantic object."""
extra = Extra.forbid
@root_validator(pre=True)
def validate_environment(cls, values: Dict) -> Dict:
"""Validate that api key exists in environment."""
github_api_key = get_from_dict_or_env(
values, "github_api_key", "GITHUB_API_KEY"
)
values["github_api_key"] = github_api_key
try:
import requests
except ImportError:
raise ImportError(
"requests is not installed. "
"Please install it with `pip install requests`"
)
return values
def _format_repo_info(self, repo: Dict) -> str:
return (
f"Repo name: {repo['name']}\n"
f"Description: {repo['description']}\n"
f"URL: {repo['html_url']}\n"
f"Stars: {repo['stargazers_count']}\n"
f"Forks: {repo['forks_count']}\n"
f"Language: {repo['language']}\n"
f"Open issues: {repo['open_issues_count']}\n"
)
def run(self, user: str) -> str:
"""Get the repository information for a specified user."""
headers = {"Authorization": f"token {self.github_api_key}"}
response = requests.get(
f"https://api.github.com/users/{user}/repos", headers=headers
)
if response.status_code != 200:
raise ValueError(f"Error: {response.status_code}, {response.text}")
repos = response.json()
repo_info = "\n\n".join(self._format_repo_info(repo) for repo in repos)
return f"Repositories for {user}:\n\n{repo_info}"

View File

@@ -21,7 +21,8 @@ def get_non_abstract_subclasses(cls: Type[BaseTool]) -> List[Type[BaseTool]]:
and subclass not in to_skip
):
subclasses.append(subclass)
subclasses.extend(get_non_abstract_subclasses(subclass))
sc = get_non_abstract_subclasses(subclass)
subclasses.extend(sc)
return subclasses