Set Up an OpenAI Account
- Visit the OpenAI website and sign up for an account if you haven't already. Next, log in to the OpenAI dashboard.
- Navigate to the API section to obtain your API key, which you will use to authenticate your requests to OpenAI's services.
- Ensure that your API key is kept secure and not exposed in public code.
Create a GitHub Repository
- Log in to your GitHub account. Click on the New Repository button to create a new repository.
- Choose a suitable name for your repository and decide if it should be public or private. Initialize the repository with a README if desired.
- Clone the repository to your local machine using the command below (replace `` with your actual repository URL):
git clone <your-repo-url>
Install Required Dependencies
- Ensure that Python is installed on your system. You can download it from the official Python website if it's not already installed.
- Use pip to install the OpenAI Python client library by executing the following command in your terminal:
pip install openai
Integrate OpenAI API with Your Code
- Create a new Python file in your cloned GitHub repository, for example, `openai_integration.py`.
- Import the OpenAI library and set up the API key at the beginning of your file:
import openai
import os
openai.api_key = os.getenv("OPENAI_API_KEY")
- To keep your API key secure, store it in an environment variable named `OPENAI_API_KEY`. If you're using a `.env` file, ensure you load these vars appropriately.
- Implement a simple API call within your Python file to test the integration, such as generating a text completion:
response = openai.Completion.create(
engine="text-davinci-003",
prompt="Once upon a time",
max_tokens=50
)
print(response.choices[0].text.strip())
Commit and Push Your Changes
- Stage your changes for commit:
git add openai_integration.py
- Commit your changes with a descriptive message:
git commit -m "Add OpenAI integration example"
- Push your changes to the remote GitHub repository:
git push origin main
Secure Your API Key
- Ensure that your `.gitignore` file includes any sensitive files, such as a local `.env` file, to prevent them from being pushed to the repository.
- If using environment variables, you can use packages like `python-dotenv` to manage them securely in development.
- Review your code repository settings to manage access and ensure that your API key, even if mistakenly committed, is not publicly available.
This guide will help you integrate OpenAI with GitHub securely and effectively, enabling the use of OpenAI's powerful capabilities within your GitHub projects.