Skip to content

Instantly share code, notes, and snippets.

@lazabogdan
Created August 21, 2024 18:50
Show Gist options
  • Save lazabogdan/94be91938a281f9f5bf6f3d79855c874 to your computer and use it in GitHub Desktop.
Save lazabogdan/94be91938a281f9f5bf6f3d79855c874 to your computer and use it in GitHub Desktop.
GitHub Gist Tools for LangChain
import os
from typing import Dict
from langchain.tools import tool
import requests
# Replace with your GitHub token or use environment variables
GITHUB_TOKEN = "your_github_token_here"
@tool
def create_gist(description: str, files: Dict[str, str], public: bool = False) -> Dict[str, str]:
"""
Create a GitHub Gist with the given description, files, and visibility.
Args:
description (str): A description of the Gist.
files (Dict[str, str]): A dictionary where keys are filenames and values are file contents.
public (bool, optional): Whether the Gist should be public. Defaults to False.
Returns:
Dict[str, str]: A dictionary containing the URL of the created Gist or an error message.
"""
url = "https://api.github.com/gists"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"description": description,
"public": public,
"files": {filename: {"content": content} for filename, content in files.items()}
}
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
return {"url": response.json()["html_url"]}
except requests.RequestException as e:
return {"error": str(e)}
@tool
def update_gist(gist_id: str, files: Dict[str, str]) -> Dict[str, str]:
"""
Update an existing GitHub Gist with the given ID and files.
Args:
gist_id (str): The ID of the Gist to update.
files (Dict[str, str]): A dictionary where keys are filenames and values are file contents.
Returns:
Dict[str, str]: A dictionary containing a success message and the URL of the updated Gist, or an error message.
"""
url = f"https://api.github.com/gists/{gist_id}"
headers = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3+json"
}
data = {
"files": {filename: {"content": content} for filename, content in files.items()}
}
try:
response = requests.patch(url, headers=headers, json=data)
response.raise_for_status()
return {"detail": "Gist updated successfully", "url": response.json()["html_url"]}
except requests.RequestException as e:
return {"error": str(e)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment