Skip to main content

OpenAI API client library for kiarina namespace

Project description

kiarina-lib-openai

A Python library for OpenAI API integration with configuration management using pydantic-settings-manager.

Features

  • Configuration Management: Use pydantic-settings-manager for flexible configuration
  • Type Safety: Full type hints and Pydantic validation
  • Secure Credential Handling: API keys are protected using SecretStr
  • Multiple Configurations: Support for multiple named configurations (e.g., different projects/environments)
  • Environment Variable Support: Configure via environment variables with KIARINA_LIB_OPENAI_ prefix
  • Custom Base URL: Support for custom OpenAI-compatible API endpoints

Installation

pip install kiarina-lib-openai

Quick Start

Basic Usage

from kiarina.lib.openai import OpenAISettings, settings_manager

# Configure OpenAI API
settings_manager.user_config = {
    "default": {
        "api_key": "sk-your-api-key-here"
    }
}

# Get settings
settings = settings_manager.settings
print(f"API Key configured: {settings.api_key.get_secret_value()[:10]}...")

Using with OpenAI Client

from openai import AsyncOpenAI
from kiarina.lib.openai import settings_manager

# Configure settings
settings_manager.user_config = {
    "default": {
        "api_key": "sk-your-api-key-here",
        "organization_id": "org-your-org-id",
        "base_url": "https://api.openai.com/v1"
    }
}

# Get client initialization arguments
settings = settings_manager.settings
client_kwargs = settings.to_client_kwargs()

# Initialize OpenAI client
client = AsyncOpenAI(**client_kwargs)

Environment Variable Configuration

Configure authentication using environment variables:

export KIARINA_LIB_OPENAI_API_KEY="sk-your-api-key-here"
export KIARINA_LIB_OPENAI_ORGANIZATION_ID="org-your-org-id"  # Optional
from kiarina.lib.openai import settings_manager

# Settings are automatically loaded from environment variables
settings = settings_manager.settings
print(f"API Key configured: {settings.api_key.get_secret_value()[:10]}...")

Multiple Configurations

Manage multiple OpenAI configurations (e.g., different projects or environments):

from kiarina.lib.openai import settings_manager

# Configure multiple projects
settings_manager.user_config = {
    "project_a": {
        "api_key": "sk-project-a-key",
        "organization_id": "org-project-a"
    },
    "project_b": {
        "api_key": "sk-project-b-key",
        "organization_id": "org-project-b"
    }
}

# Switch between configurations
settings_manager.active_key = "project_a"
project_a_settings = settings_manager.settings
print(f"Project A Org: {project_a_settings.organization_id}")

settings_manager.active_key = "project_b"
project_b_settings = settings_manager.settings
print(f"Project B Org: {project_b_settings.organization_id}")

Custom Base URL

Use with OpenAI-compatible APIs (e.g., Azure OpenAI, local models):

from kiarina.lib.openai import settings_manager

settings_manager.user_config = {
    "azure": {
        "api_key": "your-azure-key",
        "base_url": "https://your-resource.openai.azure.com/openai/deployments/your-deployment"
    }
}

settings = settings_manager.settings
print(f"Base URL: {settings.base_url}")

Configuration

This library uses pydantic-settings-manager for flexible configuration management.

OpenAISettings

The OpenAISettings class provides the following configuration fields:

Field Type Required Description
api_key SecretStr Yes OpenAI API key (masked in logs)
organization_id str | None No OpenAI organization ID
base_url str | None No Custom base URL for OpenAI-compatible APIs

Environment Variables

All settings can be configured via environment variables with the KIARINA_LIB_OPENAI_ prefix:

# API Key (required)
export KIARINA_LIB_OPENAI_API_KEY="sk-your-api-key"

# Organization ID (optional)
export KIARINA_LIB_OPENAI_ORGANIZATION_ID="org-your-org-id"

# Custom Base URL (optional)
export KIARINA_LIB_OPENAI_BASE_URL="https://api.openai.com/v1"

Programmatic Configuration

from pydantic import SecretStr
from kiarina.lib.openai import OpenAISettings, settings_manager

# Direct settings object
settings = OpenAISettings(
    api_key=SecretStr("sk-your-api-key"),
    organization_id="org-your-org-id"
)

# Via settings manager
settings_manager.user_config = {
    "default": {
        "api_key": "sk-your-api-key",  # Automatically converted to SecretStr
        "organization_id": "org-your-org-id"
    }
}

Runtime Overrides

from kiarina.lib.openai import settings_manager

# Override specific settings at runtime
settings_manager.cli_args = {
    "organization_id": "org-override-id"
}

settings = settings_manager.settings
print(f"Organization ID: {settings.organization_id}")  # Uses overridden value

Security

API Key Protection

API keys are stored using Pydantic's SecretStr type, which provides the following security benefits:

  • Masked in logs: Keys are displayed as ********** in string representations
  • Prevents accidental exposure: Keys won't appear in debug output or error messages
  • Explicit access required: Must use .get_secret_value() to access the actual key
from kiarina.lib.openai import settings_manager

settings = settings_manager.settings

# API key is masked in string representation
print(settings)  # api_key=SecretStr('**********')

# Explicit access to get the actual key
api_key = settings.api_key.get_secret_value()

API Reference

OpenAISettings

class OpenAISettings(BaseSettings):
    api_key: SecretStr
    organization_id: str | None = None
    base_url: str | None = None
    
    def to_client_kwargs(self) -> dict[str, Any]:
        """Convert settings to OpenAI client initialization arguments."""

Pydantic settings model for OpenAI API configuration.

Fields:

  • api_key (SecretStr): OpenAI API key (protected)
  • organization_id (str | None): Optional organization ID
  • base_url (str | None): Optional custom base URL for OpenAI-compatible APIs

Methods:

  • to_client_kwargs() -> dict[str, Any]: Convert settings to OpenAI client initialization arguments. Returns a dictionary with non-None values that can be passed directly to OpenAI() or AsyncOpenAI() constructors.

settings_manager

settings_manager: SettingsManager[OpenAISettings]

Global settings manager instance for OpenAI configuration. See: pydantic-settings-manager

Development

Prerequisites

  • Python 3.12+

Setup

# Clone the repository
git clone https://github.com/kiarina/kiarina-python.git
cd kiarina-python

# Setup development environment
mise run setup

Running Tests

# Run format, lint, type checks and tests
mise run package kiarina-lib-openai

# Coverage report
mise run package:test kiarina-lib-openai --coverage

Dependencies

License

This project is licensed under the MIT License - see the LICENSE file for details.

Contributing

This is a personal project, but contributions are welcome! Please feel free to submit issues or pull requests.

Related Projects

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

kiarina_lib_openai-1.31.0.tar.gz (5.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kiarina_lib_openai-1.31.0-py3-none-any.whl (5.0 kB view details)

Uploaded Python 3

File details

Details for the file kiarina_lib_openai-1.31.0.tar.gz.

File metadata

  • Download URL: kiarina_lib_openai-1.31.0.tar.gz
  • Upload date:
  • Size: 5.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for kiarina_lib_openai-1.31.0.tar.gz
Algorithm Hash digest
SHA256 8f81cdbaa150a4da8d8e02000bcc276bc093c31133cfe3507331bad447d0c7ab
MD5 aa6897fd75ff14ce3d30265b36eecb9d
BLAKE2b-256 f594df29fbef20b9b9a9a468bbe59ebd408a4a30d8a7e7a1c651db41d4b5407c

See more details on using hashes here.

File details

Details for the file kiarina_lib_openai-1.31.0-py3-none-any.whl.

File metadata

File hashes

Hashes for kiarina_lib_openai-1.31.0-py3-none-any.whl
Algorithm Hash digest
SHA256 c50475e2f222e1af29f785aeeb8ae27239debb68da1a4a2461ffdc09ee849620
MD5 a8d7585214f9ce931a2b9e13d3f0df3f
BLAKE2b-256 ffe32d59f15815658364243c45f949079b72b1f15190e233414b14c0835e4b94

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page