Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support new openai api key validation #83

Merged
merged 5 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion fastagency/studio/models/llms/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ async def create_autogen(cls, model_id: UUID, user_id: UUID, **kwargs: Any) -> s
@field_validator("api_key")
@classmethod
def validate_api_key(cls: Type["OpenAIAPIKey"], value: Any) -> Any:
if not re.match(r"^sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20}$", value):
if not re.match(
r"^(sk-(proj-|None-|svcacct-)[A-Za-z0-9_-]+|sk-[a-zA-Z0-9]{20}T3BlbkFJ[a-zA-Z0-9]{20})$",
value,
):
raise ValueError("Invalid OpenAI API Key")
return value

Expand Down
22 changes: 16 additions & 6 deletions tests/studio/models/llms/test_openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,25 @@ def test_import(monkeypatch: pytest.MonkeyPatch) -> None:


class TestOpenAIAPIKey:
def test_constructor_success(self) -> None:
@pytest.mark.parametrize(
"openai_api_key",
[
"sk-sUeBP9asw6GiYHXqtg70T3BlbkFJJuLwJFco90bOpU0Ntest", # pragma: allowlist secret
# OpenAI currently supports three prefixes for API keys:
davorrunje marked this conversation as resolved.
Show resolved Hide resolved
# project-based API key format
"sk-proj-SomeLengthStringWhichCanHave-and_inItAndTheLengthCanBeChangedAtAnyTime", # pragma: allowlist secret
# user-level API key format
"sk-None-SomeLengthStringWhichCanHave-and_inItAndTheLengthCanBeChangedAtAnyTime", # pragma: allowlist secret
# service account APi key format
"sk-svcacct-SomeLengthStringWhichCanHave-and_inItAndTheLengthCanBeChangedAtAnyTime", # pragma: allowlist secret
],
)
def test_constructor_success(self, openai_api_key: str) -> None:
api_key = OpenAIAPIKey(
api_key="sk-sUeBP9asw6GiYHXqtg70T3BlbkFJJuLwJFco90bOpU0Ntest", # pragma: allowlist secret
api_key=openai_api_key,
name="Hello World!",
) # pragma: allowlist secret
assert (
api_key.api_key
== "sk-sUeBP9asw6GiYHXqtg70T3BlbkFJJuLwJFco90bOpU0Ntest" # pragma: allowlist secret
) # pragma: allowlist secret
assert api_key.api_key == openai_api_key # pragma: allowlist secret

def test_constructor_failure(self) -> None:
with pytest.raises(ValueError, match="Invalid OpenAI API Key"):
Expand Down
Loading