Github toolkit은 LLM agent가 github repository와 상호작용할 수 있도록 하는 도구들을 포함하고 있습니다. 이 도구는 PyGitHub 라이브러리의 wrapper입니다. 모든 GithubToolkit 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요.

Setup

상위 수준에서 다음을 수행합니다:
  1. pygithub 라이브러리 설치
  2. Github app 생성
  3. 환경 변수 설정
  4. toolkit.get_tools()를 사용하여 agent에 도구 전달
개별 도구의 자동 추적을 활성화하려면 LangSmith API key를 설정하세요:
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"

Installation

1. 의존성 설치

이 integration은 langchain-community에 구현되어 있습니다. pygithub 의존성도 필요합니다:
pip install -qU  pygithub langchain-community

2. Github App 생성

Github app을 생성하고 등록하려면 여기의 지침을 따르세요. app이 다음 repository 권한을 가지고 있는지 확인하세요:
  • Commit statuses (읽기 전용)
  • Contents (읽기 및 쓰기)
  • Issues (읽기 및 쓰기)
  • Metadata (읽기 전용)
  • Pull requests (읽기 및 쓰기)
app이 등록되면, app이 작동할 각 repository에 대한 권한을 부여해야 합니다. github.com의 App 설정을 사용하세요.

3. 환경 변수 설정

agent를 초기화하기 전에 다음 환경 변수를 설정해야 합니다:
  • GITHUB_APP_ID- app의 일반 설정에서 찾을 수 있는 6자리 숫자
  • GITHUB_APP_PRIVATE_KEY- app의 private key .pem 파일 위치 또는 해당 파일의 전체 텍스트를 문자열로
  • GITHUB_REPOSITORY- bot이 작동할 Github repository의 이름. {username}/{repo-name} 형식을 따라야 합니다. app이 먼저 이 repository에 추가되었는지 확인하세요!
  • 선택사항: GITHUB_BRANCH- bot이 commit을 수행할 branch. 기본값은 repo.default_branch입니다.
  • 선택사항: GITHUB_BASE_BRANCH- PR이 기반할 repo의 base branch. 기본값은 repo.default_branch입니다.
import getpass
import os

for env_var in [
    "GITHUB_APP_ID",
    "GITHUB_APP_PRIVATE_KEY",
    "GITHUB_REPOSITORY",
]:
    if not os.getenv(env_var):
        os.environ[env_var] = getpass.getpass()

Instantiation

이제 toolkit을 인스턴스화할 수 있습니다:
from langchain_community.agent_toolkits.github.toolkit import GitHubToolkit
from langchain_community.utilities.github import GitHubAPIWrapper

github = GitHubAPIWrapper()
toolkit = GitHubToolkit.from_github_api_wrapper(github)

Tools

사용 가능한 도구 보기:
tools = toolkit.get_tools()

for tool in tools:
    print(tool.name)
Get Issues
Get Issue
Comment on Issue
List open pull requests (PRs)
Get Pull Request
Overview of files included in PR
Create Pull Request
List Pull Requests' Files
Create File
Read File
Update File
Delete File
Overview of existing files in Main branch
Overview of files in current working branch
List branches in this repository
Set active branch
Create a new branch
Get files from a directory
Search issues and pull requests
Search code
Create review request
이러한 도구의 목적은 다음과 같습니다: 각 단계는 아래에서 자세히 설명됩니다.
  1. Get Issues- repository에서 issue를 가져옵니다.
  2. Get Issue- 특정 issue에 대한 세부 정보를 가져옵니다.
  3. Comment on Issue- 특정 issue에 댓글을 게시합니다.
  4. Create Pull Request- bot의 작업 branch에서 base branch로 pull request를 생성합니다.
  5. Create File- repository에 새 파일을 생성합니다.
  6. Read File- repository에서 파일을 읽습니다.
  7. Update File- repository의 파일을 업데이트합니다.
  8. Delete File- repository에서 파일을 삭제합니다.

Include release tools

기본적으로 toolkit은 release 관련 도구를 포함하지 않습니다. toolkit을 초기화할 때 include_release_tools=True를 설정하여 포함할 수 있습니다:
toolkit = GitHubToolkit.from_github_api_wrapper(github, include_release_tools=True)
include_release_tools=True를 설정하면 다음 도구가 포함됩니다:
  • Get Latest Release- repository에서 최신 release를 가져옵니다.
  • Get Releases- repository에서 최신 5개의 release를 가져옵니다.
  • Get Release- tag 이름(예: v1.0.0)으로 repository에서 특정 release를 가져옵니다.

Use within an agent

LLM 또는 chat model이 필요합니다:
# | output: false
# | echo: false

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
도구의 하위 집합으로 agent를 초기화합니다:
from langchain.agents import create_agent


tools = [tool for tool in toolkit.get_tools() if tool.name == "Get Issue"]
assert len(tools) == 1
tools[0].name = "get_issue"

agent_executor = create_agent(llm, tools)
그리고 쿼리를 실행합니다:
example_query = "What is the title of issue 24888?"

events = agent_executor.stream(
    {"messages": [("user", example_query)]},
    stream_mode="values",
)
for event in events:
    event["messages"][-1].pretty_print()
================================ Human Message =================================

What is the title of issue 24888?
================================== Ai Message ==================================
Tool Calls:
  get_issue (call_iSYJVaM7uchfNHOMJoVPQsOi)
 Call ID: call_iSYJVaM7uchfNHOMJoVPQsOi
  Args:
    issue_number: 24888
================================= Tool Message =================================
Name: get_issue

{"number": 24888, "title": "Standardize KV-Store Docs", "body": "To make our KV-store integrations as easy to use as possible we need to make sure the docs for them are thorough and standardized. There are two parts to this: updating the KV-store docstrings and updating the actual integration docs.\r\n\r\nThis needs to be done for each KV-store integration, ideally with one PR per KV-store.\r\n\r\nRelated to broader issues #21983 and #22005.\r\n\r\n## Docstrings\r\nEach KV-store class docstring should have the sections shown in the [Appendix](#appendix) below. The sections should have input and output code blocks when relevant.\r\n\r\nTo build a preview of the API docs for the package you're working on run (from root of repo):\r\n\r\n\`\`\`shell\r\nmake api_docs_clean; make api_docs_quick_preview API_PKG=openai\r\n\`\`\`\r\n\r\nwhere `API_PKG=` should be the parent directory that houses the edited package (e.g. community, openai, anthropic, huggingface, together, mistralai, groq, fireworks, etc.). This should be quite fast for all the partner packages.\r\n\r\n## Doc pages\r\nEach KV-store [docs page](https://python.langchain.com/docs/integrations/stores/) should follow [this template](https://github.com/langchain-ai/langchain/blob/master/libs/cli/langchain_cli/integration_template/docs/kv_store.ipynb).\r\n\r\nHere is an example: https://python.langchain.com/docs/integrations/stores/in_memory/\r\n\r\nYou can use the `langchain-cli` to quickly get started with a new chat model integration docs page (run from root of repo):\r\n\r\n\`\`\`shell\r\npoetry run pip install -e libs/cli\r\npoetry run langchain-cli integration create-doc --name \"foo-bar\" --name-class FooBar --component-type kv_store --destination-dir ./docs/docs/integrations/stores/\r\n\`\`\`\r\n\r\nwhere `--name` is the integration package name without the \"langchain-\" prefix and `--name-class` is the class name without the \"ByteStore\" suffix. This will create a template doc with some autopopulated fields at docs/docs/integrations/stores/foo_bar.ipynb.\r\n\r\nTo build a preview of the docs you can run (from root):\r\n\r\n\`\`\`shell\r\nmake docs_clean\r\nmake docs_build\r\ncd docs/build/output-new\r\nyarn\r\nyarn start\r\n\`\`\`\r\n\r\n## Appendix\r\nExpected sections for the KV-store class docstring.\r\n\r\n\`\`\`python\r\n    \"\"\"__ModuleName__ completion KV-store integration.\r\n\r\n    # TODO: Replace with relevant packages, env vars.\r\n    Setup:\r\n        Install `__package_name__` and set environment variable `__MODULE_NAME___API_KEY`.\r\n\r\n        .. code-block:: bash\r\n\r\n            pip install -U __package_name__\r\n            export __MODULE_NAME___API_KEY=\"your-api-key\"\r\n\r\n    # TODO: Populate with relevant params.\r\n    Key init args \u2014 client params:\r\n        api_key: Optional[str]\r\n            __ModuleName__ API key. If not passed in will be read from env var __MODULE_NAME___API_KEY.\r\n\r\n    See full list of supported init args and their descriptions in the params section.\r\n\r\n    # TODO: Replace with relevant init params.\r\n    Instantiate:\r\n        .. code-block:: python\r\n\r\n            from __module_name__ import __ModuleName__ByteStore\r\n\r\n            kv_store = __ModuleName__ByteStore(\r\n                # api_key=\"...\",\r\n                # other params...\r\n            )\r\n\r\n    Set keys:\r\n        .. code-block:: python\r\n\r\n            kv_pairs = [\r\n                [\"key1\", \"value1\"],\r\n                [\"key2\", \"value2\"],\r\n            ]\r\n\r\n            kv_store.mset(kv_pairs)\r\n\r\n        .. code-block:: python\r\n\r\n    Get keys:\r\n        .. code-block:: python\r\n\r\n            kv_store.mget([\"key1\", \"key2\"])\r\n\r\n        .. code-block:: python\r\n\r\n            # TODO: Example output.\r\n\r\n    Delete keys:\r\n        ..code-block:: python\r\n\r\n            kv_store.mdelete([\"key1\", \"key2\"])\r\n\r\n        ..code-block:: python\r\n    \"\"\"  # noqa: E501\r\n\`\`\`", "comments": "[]", "opened_by": "jacoblee93"}
================================== Ai Message ==================================

The title of issue 24888 is "Standardize KV-Store Docs".

API reference

모든 GithubToolkit 기능 및 구성에 대한 자세한 문서는 API reference를 참조하세요.
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I