🔍 Code Extractor

function init_openai_client

Maturity: 41

Initializes the OpenAI client by setting the API key from either a provided parameter or environment variable.

File:
/tf/active/vicechatdev/chromadb-cleanup/src/summarization/summarizer.py
Lines:
7 - 19
Complexity:
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

  • openai
  • os

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

    Validates the presence of required API keys (OpenAI and SERPER) and sets them as environment variables with fallback default values.

    From: /tf/active/vicechatdev/find_email/test_enrichment.py
  • class LLMClient_v1 45.5% similar

    A client class for interacting with Large Language Models (LLMs), specifically designed to work with OpenAI's chat completion API.

    From: /tf/active/vicechatdev/QA_updater/core/llm_client.py
  • function get_filecloud_client 44.5% similar

    Singleton factory function that returns a globally cached FileCloud API client instance, handling initialization, authentication, and re-authentication as needed.

    From: /tf/active/vicechatdev/CDocs/controllers/filecloud_controller.py
  • function test_configuration_v1 44.3% similar

    Validates that all required configuration variables (Azure AD credentials, OpenAI API key, and domain) are properly set and not using placeholder values.

    From: /tf/active/vicechatdev/find_email/test_vendor_extractor.py
  • class TestLLMClient 41.1% similar

    Unit test class for testing the LLMClient class, which provides comprehensive test coverage for initialization, text generation, structured data extraction, and error handling across multiple LLM providers (OpenAI, Anthropic, Azure, local).

    From: /tf/active/vicechatdev/invoice_extraction/tests/test_utils.py
← Back to Browse