Files
dify-plugin-sdks/python/examples/github/tools/github_repositories.py
T
Maries c6f83a63e1 feat[0.4.2]: Tool OAuth (#179)
* chore: fix ruff issue

* feat(oauth): implement OAuth

* feat(invoke-message): refactor message handling and introduce InvokeMessage class

* feat(plugin-oauth): add credential_id and credential_type to tool parameters

* feat(plugin-oauth): add credential_id and credential_type to tool parameters

* chore: update dify_plugin version to 0.5.0b4 and clean up github.yaml

* chore: update plugin version to 0.1.2 in manifest.yaml

* feat(session): session context and tool backwards invocation credential support

* feat(oauth): session context and tool backwards invocation credential support

* feat: update README and requirements for OAuth support in version 0.4.2

* feat: add .gitignore to exclude IDE files and secret keys

* chore: apply ruff

* feat: bump version to 0.4.2b1

* feat: update GitHub plugin configuration for OAuth support and improve credential handling

* feat: update .gitignore to exclude dify plugin files and public keys

* feat: fix credential validation for GitHub API and bump version to 0.2.1

* feat: update GitHub plugin to support multiple access tokens and bump version to 0.2.5

* chore: apply ruff

* feat: add ToolProviderOAuthError for improved OAuth error handling in GitHub plugin

* chore: apply ruff

* chore: bump version to 0.4.2

* chore: update examples sdk version to 0.4.2

* fix: thread deadlock in PluginRunner when running tests without gevent monkey patching

* feat: add support for refreshing OAuth credentials in Plugin and GitHub provider

* feat: refactor OAuth credential handling to return structured OAuthCredentials object

* apply ruff

* feat: refactor OAuth credential handling to use ToolOAuthCredentials for improved structure

* feat: reorganize imports in __init__.py for improved clarity and structure

* feat: add Microsoft To Do plugin for refresh token example

* chore: apply ruff

* fix: update author in GitHub configuration and clean up Microsoft To Do schema

* chore: bump version to 0.4.2b2 in pyproject.toml

* feat: update Microsoft To Do plugin to handle OAuth token encoding and version bump

* feat:remove inelegant example

* chore: update dify_plugin version to 0.4.2

* chore: bump version to 0.4.2 in pyproject.toml

---------

Co-authored-by: Yeuoly <admin@srmxy.cn>
2025-07-23 13:49:01 +08:00

81 lines
3.6 KiB
Python

import json
from collections.abc import Generator
from datetime import datetime
from typing import Any
from urllib.parse import quote
import requests
from dify_plugin import Tool
from dify_plugin.entities.provider_config import CredentialType
from dify_plugin.entities.tool import ToolInvokeMessage
class GithubRepositoriesTool(Tool):
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage, None, None]:
"""
invoke tools
"""
top_n = tool_parameters.get("top_n", 5)
query = tool_parameters.get("query", "")
credential_type = self.runtime.credential_type
if not query:
yield self.create_text_message("Please input symbol")
if credential_type == CredentialType.API_KEY and "access_tokens" not in self.runtime.credentials:
yield self.create_text_message("GitHub API Access Tokens is required.")
if credential_type == CredentialType.OAUTH and "access_tokens" not in self.runtime.credentials:
yield self.create_text_message("GitHub OAuth Access Tokens is required.")
access_token = self.runtime.credentials.get("access_tokens")
try:
headers = {
"Content-Type": "application/vnd.github+json",
"Authorization": f"Bearer {access_token}",
# fixed api version
"X-GitHub-Api-Version": "2022-11-28",
}
s = requests.session()
api_domain = "https://api.github.com"
response = s.request(
method="GET",
headers=headers,
url=f"{api_domain}/search/repositories?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 = []
if len(response_data.get("items")) > 0:
for item in response_data.get("items"):
content = {}
updated_at_object = datetime.strptime(item["updated_at"], "%Y-%m-%dT%H:%M:%SZ")
content["owner"] = item["owner"]["login"]
content["name"] = item["name"]
if item["description"] is not None:
content["description"] = (
item["description"][:100] + "..."
if len(item["description"]) > 100
else item["description"]
)
else:
content["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()
yield self.create_text_message(
self.session.model.summary.invoke(
text=json.dumps(contents, ensure_ascii=False),
instruction="Summarize the text",
)
)
else:
yield self.create_text_message(f"No items related to {query} were found.")
else:
yield self.create_text_message(response.json().get("message"))
except Exception as e:
yield self.create_text_message(f"GitHub API Key and Api Version is invalid. {e}")