Integrate OpenAI with CircleCI
- Begin by creating an OpenAI API key from the OpenAI Dashboard. It will be needed to authenticate requests to the OpenAI API.
- Make sure your CircleCI project is set up and a `config.yml` file is present in the `.circleci` directory at the root of your repository.
Add OpenAI API Key to CircleCI Environment Variables
- Navigate to the CircleCI project dashboard, and find the project you are working on.
- Go to the settings of the project and find the "Environment Variables" section.
- Add a new environment variable with the name `OPENAI_API_KEY` and the value as your OpenAI API key.
Modify Your Application Code to Use OpenAI
- If not already done, install the OpenAI Python/Node.js client (or any applicable library for your language). For Python, you may need:
pip install openai
- For a Node.js environment, use:
npm install openai
- Write a function to call OpenAI API using the client. Here’s an example using Python:
import os
import openai
def call_openai_api(prompt):
api_key = os.getenv("OPENAI_API_KEY")
openai.api_key = api_key
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=100
)
return response.choices[0].text.strip()
Set Up CircleCI Configuration
- In the `.circleci/config.yml` file, ensure you're running CI steps in an environment conducive to your project (e.g., an appropriate Docker image).
- Add a step that runs your application or test script which involves OpenAI functionality. Here's a YAML snippet for a Python project:
version: 2.1
jobs:
build:
docker:
- image: circleci/python:3.8
steps:
- checkout
- run:
name: Install Dependencies
command: |
python -m venv venv
. venv/bin/activate
pip install -r requirements.txt
- run:
name: Run OpenAI Script
command: |
. venv/bin/activate
python your_script.py
Testing and Debugging Integration
- Commit and push the updated configuration and source code to trigger a CircleCI build.
- Access the CircleCI dashboard to monitor the build process. Check the logs to verify successful connection to the OpenAI API.
- If issues arise, ensure that the environment variable is correctly typed and available in your CircleCI configuration. Additionally, double-check any network-related settings or connectivity permissions.
Optimize and Secure Your Configuration
- Ensure that you are handling any sensitive data securely throughout your CI/CD pipeline. Consider encrypting secrets if necessary.
- Regularly update dependencies in your project to maintain compatibility and security standards.