Skip to content

Instantly share code, notes, and snippets.

@cyberpunk042
Last active August 16, 2024 21:51
Show Gist options
  • Save cyberpunk042/3234ac9e550edc1197f3842e48c83b93 to your computer and use it in GitHub Desktop.
Save cyberpunk042/3234ac9e550edc1197f3842e48c83b93 to your computer and use it in GitHub Desktop.
Snippet to query openai with composio using a prompt and a given list of tools actions. The query can then make calls to the integrated tools.

Composio Toolset Integration with OpenAI (Github & Google)

For Developers, Technicians & Engineers

This project integrates GitHub and other developer-focused services using the Composio Toolset. It provides essential actions for automating tasks related to repository management, collaboration, and more. (Uses OpenAI API and Composio API)

Get Started with It

Requirements

  1. Open AI API Registration: Sign up for a OpenAI account if you haven’t already.
  2. Composio Registration: Sign up for a Composio account if you haven’t already.
  3. Tool Registration: Register and integrate the tools you need, such as GitHub.

Python Setup

To install the necessary Python packages, run:

pip install -r requirements.txt

Add a GitHub Integration

To add GitHub integration to your Composio setup, run:

composio add github

This command will open an interactive session in your browser to authenticate and configure the GitHub integration with Composio.

COMPOSIO Actions: https://raw.githubusercontent.com/ComposioHQ/composio/master/python/composio/client/enums/_action.py

Relevant GitHub Actions

These GitHub actions are commonly used by developers and IT professionals for managing repositories, issues, and pull requests. For a complete list of available actions, you can refer to the Composio Action Enum Source.

Repository Management

  • 'GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER': Star a repository.
  • 'GITHUB_CREATE_AN_ISSUE': Create an issue in a repository.
  • 'GITHUB_CREATE_A_PULL_REQUEST': Create a pull request in a repository.
  • 'GITHUB_SEARCH_CODE': Search for code within repositories.
  • 'GITHUB_SEARCH_REPOSITORIES': Search for repositories.
  • 'GITHUB_GET_A_REPOSITORY': Get details about a repository.

Collaboration & Workflow Automation

  • 'GITHUB_ADD_ASSIGNEES_TO_AN_ISSUE': Assign users to an issue.
  • 'GITHUB_LIST_ISSUES_ASSIGNED_TO_THE_AUTHENTICATED_USER': List issues assigned to the authenticated user.
  • 'GITHUB_CREATE_A_REPOSITORY_WEBHOOK': Create a webhook for repository events.

Insights & Security

  • 'GITHUB_GET_REPOSITORY_LANGUAGES': Get the languages used in a repository.
  • 'GITHUB_GET_COMMUNITY_PROFILE_METRICS': Retrieve community profile metrics for a repository.
  • 'GITHUB_GET_REPOSITORY_SECURITY_ADVISORIES': Get security advisories for a repository.

Additional Tools for IT Automation

Google Services

Automate tasks using Google services such as Google Drive and Gmail.

  • Google Drive

    • 'GOOGLEDRIVE_FIND_FILE': Search for a file in Google Drive.
    • 'GOOGLEDRIVE_CREATE_FILE_FROM_TEXT': Create a new file in Google Drive from text content.
  • Gmail

    • 'GMAIL_SEND_EMAIL': Send an email via Gmail.
    • 'GMAIL_CREATE_EMAIL_DRAFT': Create a draft email in Gmail.

GitLab

Manage CI/CD pipelines and Git repositories with GitLab.

  • 'GITLAB_CREATE_PROJECT_REPOSITORY_BRANCH': Create a new branch in a GitLab project repository.
  • 'GITLAB_DELETE_PROJECT_REPOSITORY_BRANCH': Delete a branch in a GitLab project repository.

Usage Examples

Example 1: Star a GitHub Repo and Create an Issue

This example stars a GitHub repository and creates an issue in it.

python script_name.py --openai_api_key 'your_openai_api_key' --composio_api_key 'your_composio_api_key' --task 'Star a repo and create a new issue' --actions 'GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER' 'GITHUB_CREATE_AN_ISSUE'

Example 2: Search for Code and Repositories on GitHub

This example searches for specific code and repositories on GitHub.

python script_name.py --openai_api_key 'your_openai_api_key' --composio_api_key 'your_composio_api_key' --task 'Search for a specific code snippet in repositories' --actions 'GITHUB_SEARCH_CODE' 'GITHUB_SEARCH_REPOSITORIES'

Example 3: Automate Google Drive and Gmail Tasks

This example finds a file in Google Drive and then sends an email via Gmail.

python script_name.py --openai_api_key 'your_openai_api_key' --composio_api_key 'your_composio_api_key' --task 'Find a file in Google Drive and send an email' --actions 'GOOGLEDRIVE_FIND_FILE' 'GMAIL_SEND_EMAIL'

Example 4: Save Response to a File

This example stars a GitHub repository and creates an issue, saving the response to a file.

python script_name.py --openai_api_key 'your_openai_api_key' --composio_api_key 'your_composio_api_key' --task 'Star a repo and create a new issue' --actions 'GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER' 'GITHUB_CREATE_AN_ISSUE' --output_file 'output.txt'

Logging and Error Handling

The script logs actions and errors during execution, making it easier to debug and track issues. If an error occurs, it will be logged and raised appropriately. Additionally, if specified, the script can save the chat completion response to a file.

Additional Resources

For further customization and advanced use cases, refer to the Composio Documentation for more detailed instructions and examples.

import os
import logging
import argparse
from openai import OpenAI
from composio_openai import ComposioToolSet, App, Action
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def initialize_openai(api_key):
"""
Initialize the OpenAI client with the provided API key.
Args:
api_key (str): The OpenAI API key.
Returns:
OpenAI: The initialized OpenAI client.
Raises:
ValueError: If the API key is not provided.
"""
if not api_key:
logger.error("OpenAI API Key is required.")
raise ValueError("OpenAI API Key is required.")
try:
client = OpenAI(api_key=api_key)
logger.info("OpenAI client initialized successfully.")
return client
except Exception as e:
logger.error(f"Failed to initialize OpenAI client: {e}")
raise
def initialize_composio_toolset(api_key):
"""
Initialize the Composio Tool Set with the provided API key.
Args:
api_key (str): The Composio API key.
Returns:
ComposioToolSet: The initialized Composio Tool Set.
Raises:
ValueError: If the API key is not provided.
"""
if not api_key:
logger.error("Composio API Key is required.")
raise ValueError("Composio API Key is required.")
try:
toolset = ComposioToolSet(api_key=api_key)
logger.info("Composio Tool Set initialized successfully.")
return toolset
except Exception as e:
logger.error(f"Failed to initialize Composio Tool Set: {e}")
raise
def get_composio_tools(toolset, action_names):
"""
Fetch the specified Composio tools based on action names.
Args:
toolset (ComposioToolSet): The initialized Composio Tool Set.
action_names (list): List of action names to fetch.
Returns:
list: The fetched Composio tools.
Raises:
Exception: If fetching tools fails.
"""
try:
# Map action names to Composio Action objects
action_objects = []
for action_name in action_names:
if hasattr(Action, action_name):
action_objects.append(getattr(Action, action_name))
else:
logger.warning(f"Action '{action_name}' is not a valid Composio action.")
tools = toolset.get_actions(actions=action_objects)
logger.info("Composio tools fetched successfully.")
return tools
except Exception as e:
logger.error(f"Failed to fetch Composio tools: {e}")
raise
def create_chat_completion(openai_client, tools, task):
"""
Create a chat completion request using the OpenAI client.
Args:
openai_client (OpenAI): The initialized OpenAI client.
tools (list): The tools to pass to the chat completion.
task (str): The task description for the chat completion.
Returns:
dict: The response from the chat completion request.
Raises:
Exception: If the chat completion request fails.
"""
try:
response = openai_client.chat.completions.create(
model="gpt-4-turbo",
tools=tools,
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": task}
]
)
logger.info("Chat completion request created successfully.")
return response
except Exception as e:
logger.error(f"Failed to create chat completion: {e}")
raise
def save_response_to_file(response, output_file):
"""
Save the chat completion response to a file.
Args:
response (dict): The response from the chat completion request.
output_file (str): The file path to save the response.
Raises:
IOError: If saving the file fails.
"""
try:
with open(output_file, 'w') as file:
file.write(response)
logger.info(f"Response saved to file: {output_file}")
except IOError as e:
logger.error(f"Failed to save response to file: {e}")
raise
def main(openai_api_key, composio_api_key, task, action_names, output_file=None):
"""
Main function to orchestrate the task execution.
Args:
openai_api_key (str): The OpenAI API key.
composio_api_key (str): The Composio API key.
task (str): The task description for the chat completion.
action_names (list): List of action names to use.
output_file (str): Optional file path to save the response.
"""
try:
# Initialize the OpenAI client
openai_client = initialize_openai(openai_api_key)
# Initialize the Composio Tool Set
composio_toolset = initialize_composio_toolset(composio_api_key)
# Get the specified Composio tools
tools = get_composio_tools(composio_toolset, action_names)
# Create chat completion request
response = create_chat_completion(openai_client, tools, task)
# Extract the response content
response_content = response["choices"][0]["message"]["content"]
# Save the response to a file if specified
if output_file:
save_response_to_file(response_content, output_file)
else:
# Print the response to the console
print(response_content)
except Exception as e:
logger.error(f"An error occurred during execution: {e}")
raise
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Run a chat completion with OpenAI and Composio Tool Set.")
parser.add_argument("--openai_api_key", required=True, help="OpenAI API Key")
parser.add_argument("--composio_api_key", required=True, help="Composio API Key")
parser.add_argument("--task", required=True, help="Task description for the chat completion")
parser.add_argument("--actions", nargs='+', required=True, help="List of action names to fetch and use")
parser.add_argument("--output_file", help="Optional file path to save the response")
args = parser.parse_args()
main(
openai_api_key=args.openai_api_key,
composio_api_key=args.composio_api_key,
task=args.task,
action_names=args.actions,
output_file=args.output_file
)
composio_core==0.4.3
composio_openai==0.4.3
openai==1.40.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment