Description
The Model class provides a straightforward way to configure and manage OpenAI-based API clients. It validates and stores both the model name and the API key, automatically initializing a matching OpenAI client for you.
Use the Model class to simplify how you manage different OpenAI models and keys across your chatbot applications.
Use the Model class to simplify how you manage different OpenAI models and keys across your chatbot applications.
- Purpose: Encapsulate the details of model configuration (e.g., the model name, API key, and associated client) to simplify usage within your application.
- Validation: Ensures both the API key and model name meet the required formats and are tested before actual usage.
- Automatic Client Creation: Whenever you update the API key, a new OpenAI client is initialized if validation succeeds.
Attributes
| Attribute | Type | Description |
|---|---|---|
| model_api_key | str | Your OpenAI secret key ("sk-..."). Changing it re-initialises the client. |
| model_model | str | Model name (default: "gpt-4o"). |
| model_client | openai.OpenAI | The underlying OpenAI python-client, auto-created on first access. |
Methods
| Method | Returns | Purpose |
|---|---|---|
| model_model (getter) | str | Retrieves the currently set model name. |
| model_model (setter) | None | Validates and sets a new model name. Raises an Exception if the new name is not in the accepted list of models. |
| model_api_key (getter) | str | Retrieves the currently stored API key. |
| model_api_key (setter) | None | Validates the format of the new API key (must start with 'sk-' and be at least 20 characters). Performs a test request to ensure the key is valid. If successful, updates the API key and re-initializes the client. |
| model_client (getter) | openai.OpenAI | Retrieves the OpenAI client currently in use. |
| model_client (setter) | None | Explicitly sets a new OpenAI client by providing the same API key already stored in model_api_key. If the provided key does not match the stored one, an exception is raised. |
Example
Code
from chatweaver import Model
# Initialize the Model with a valid API key and optionally specify the model name
model_instance = Model(api_key="sk-1234567890abcdef1234", model="gpt-4o")
# Check basic info
print(str(model_instance))
# Example Output: <Model | model=gpt-4o, api_key=sk-1234567...4564>
# Update the model name (must be in the allowed set of models)
model_instance.model_model = "gpt-4o"
# Update the API key (re-initializes the OpenAI client if validation succeeds)
model_instance.model_api_key = "sk-0987654321abcdef5678"
# Retrieve the OpenAI client to make requests manually (if needed)
client = model_instance.model_client
# Compare with another Model instance
another_model = Model(api_key="sk-0987654321abcdef5678", model="gpt-4o")
print(model_instance == another_model) # True, if both model name and API key match