Skip to content

Commit

Permalink
method to get instance of OpenAI client, creating the client only whe…
Browse files Browse the repository at this point in the history
…n it's needed, preventing test errors at module level when no API key
  • Loading branch information
iQuxLE committed Aug 29, 2024
1 parent 6fd0080 commit 71889f8
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions src/curate_gpt/extract/openai_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@

import json
import logging
import os
from dataclasses import dataclass
from typing import List

from openai import OpenAI

client = OpenAI()
from openai import OpenAI, OpenAIError

from curate_gpt.extract.extractor import AnnotatedObject, Extractor

Expand All @@ -27,6 +26,18 @@ class OpenAIExtractor(Extractor):
# conversation: List[Dict[str, Any]] = None
# conversation_mode: bool = False

@staticmethod
def _get_openai_client():
"""
Private method to get an instance of the OpenAI client.
"""
api_key = os.getenv("OPENAI_API_KEY")
if api_key is None:
raise OpenAIError(
"The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
)
return OpenAI(api_key=api_key)

def functions(self):
return [
{
Expand Down Expand Up @@ -91,6 +102,8 @@ def extract(
}
)
# print(yaml.dump(messages))
client = self._get_openai_client()

response = client.chat.completions.create(
model=self.model,
functions=self.functions(),
Expand Down

0 comments on commit 71889f8

Please sign in to comment.