function init_openai_client
Initializes the OpenAI client by setting the API key from either a provided parameter or environment variable.
/tf/active/vicechatdev/chromadb-cleanup/src/summarization/summarizer.py
7 - 19
simple
Purpose
This function configures the OpenAI library with authentication credentials required for making API calls. It provides flexible initialization by accepting an API key directly or falling back to the OPENAI_API_KEY environment variable. If neither is available, it raises an error to prevent unauthenticated API calls.
Source Code
def init_openai_client(api_key=None):
"""
Initialize the OpenAI client with the API key.
Args:
api_key: OpenAI API key
"""
if api_key:
openai.api_key = api_key
elif "OPENAI_API_KEY" in os.environ:
openai.api_key = os.environ["OPENAI_API_KEY"]
else:
raise ValueError("OpenAI API key not provided. Set OPENAI_API_KEY environment variable or pass api_key.")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
api_key |
- | None | positional_or_keyword |
Parameter Details
api_key: Optional string parameter containing the OpenAI API key. If None, the function attempts to retrieve the key from the OPENAI_API_KEY environment variable. Expected format is a valid OpenAI API key string (typically starts with 'sk-').
Return Value
This function returns None. It performs a side effect by setting the openai.api_key global variable, which configures the OpenAI library for subsequent API calls.
Dependencies
openaios
Required Imports
import os
import openai
Usage Example
import os
import openai
# Method 1: Pass API key directly
init_openai_client(api_key='sk-your-api-key-here')
# Method 2: Use environment variable
os.environ['OPENAI_API_KEY'] = 'sk-your-api-key-here'
init_openai_client()
# After initialization, you can use OpenAI API
response = openai.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[{'role': 'user', 'content': 'Hello!'}]
)
Best Practices
- Always call this function before making any OpenAI API calls to ensure proper authentication
- Store API keys securely using environment variables rather than hardcoding them in source code
- Handle the ValueError exception when calling this function to provide user-friendly error messages
- Consider calling this function once during application initialization rather than repeatedly
- Ensure the API key has appropriate permissions for the operations you intend to perform
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_setup 60.5% similar
-
class LLMClient_v1 45.5% similar
-
function get_filecloud_client 44.5% similar
-
function test_configuration_v1 44.3% similar
-
class TestLLMClient 41.1% similar