Skip to content

Commit

Permalink
fix(openai): validate api key
Browse files Browse the repository at this point in the history
  • Loading branch information
mamadoudicko committed Aug 29, 2023
1 parent 68eb3ca commit 93b3fb3
Show file tree
Hide file tree
Showing 5 changed files with 110 additions and 51 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { Brain } from "@/lib/context/BrainProvider/types";
import { defineMaxTokens } from "@/lib/helpers/defineMaxTokens";
import { useToast } from "@/lib/hooks";

import { checkOpenAIKey } from "../utils/checkOpenAIKey";
import { validateOpenAIKey } from "../utils/validateOpenAIKey";

type UseSettingsTabProps = {
brainId: UUID;
Expand Down Expand Up @@ -220,25 +220,23 @@ export const useSettingsTab = ({ brainId }: UseSettingsTabProps) => {
return;
}

if (openai_api_key !== undefined) {
if (!(await checkOpenAIKey(openai_api_key))) {
publish({
variant: "danger",
text: t("invalidOpenAIKey", { ns: "config" }),
});

return;
}
if (
openai_api_key !== undefined &&
!(await validateOpenAIKey(
openai_api_key,
{
badApiKeyError: t("incorrectApiKey", { ns: "config" }),
invalidApiKeyError: t("invalidApiKeyError", { ns: "config" }),
},
publish
))
) {
return;
}

try {
setIsUpdating(true);
const {
maxTokens: max_tokens,
openai_api_key,
prompt,
...otherConfigs
} = getValues();
const { maxTokens: max_tokens, prompt, ...otherConfigs } = getValues();

if (
dirtyFields["prompt"] &&
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import axios from "axios";

import { ToastData } from "@/lib/components/ui/Toast/domain/types";
import { getAxiosErrorParams } from "@/lib/helpers/getAxiosErrorParams";

export const getOpenAIKeyValidationStatusCode = async (
key: string
): Promise<number> => {
const url = "https://api.openai.com/v1/chat/completions";
const headers = {
Authorization: `Bearer ${key}`,
"Content-Type": "application/json",
};

const data = JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{
role: "user",
content: "Hello!",
},
],
});

try {
await axios.post(url, data, { headers });

return 200;
} catch (error) {
return getAxiosErrorParams(error)?.status ?? 400;
}
};

type ErrorMessages = {
badApiKeyError: string;
invalidApiKeyError: string;
};

export const validateOpenAIKey = async (
openai_api_key: string | undefined,
errorMessages: ErrorMessages,
publish: (toast: ToastData) => void
): Promise<boolean> => {
if (openai_api_key !== undefined) {
const keyValidationStatusCode = await getOpenAIKeyValidationStatusCode(
openai_api_key
);

if (keyValidationStatusCode !== 200) {
if (keyValidationStatusCode === 401) {
publish({
variant: "danger",
text: errorMessages.badApiKeyError,
});
}

if (keyValidationStatusCode === 429) {
publish({
variant: "danger",
text: errorMessages.invalidApiKeyError,
});
}

return false;
}

return true;
}

return false;
};
21 changes: 21 additions & 0 deletions frontend/app/user/components/ApiKeyConfig/hooks/useApiKeyConfig.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/* eslint-disable max-lines */
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";

import { validateOpenAIKey } from "@/app/brains-management/[brainId]/components/BrainManagementTabs/components/SettingsTab/utils/validateOpenAIKey";
import { useAuthApi } from "@/lib/api/auth/useAuthApi";
import { useUserApi } from "@/lib/api/user/useUserApi";
import { UserIdentity } from "@/lib/api/user/user";
Expand All @@ -20,6 +22,7 @@ export const useApiKeyConfig = () => {
const { createApiKey } = useAuthApi();
const { publish } = useToast();
const [userIdentity, setUserIdentity] = useState<UserIdentity>();
const { t } = useTranslation(["config"]);

const fetchUserIdentity = async () => {
setUserIdentity(await getUserIdentity());
Expand Down Expand Up @@ -56,6 +59,24 @@ export const useApiKeyConfig = () => {
const changeOpenAiApiKey = async () => {
try {
setChangeOpenAiApiKeyRequestPending(true);

if (
openAiApiKey !== undefined &&
openAiApiKey !== null &&
!(await validateOpenAIKey(
openAiApiKey,
{
badApiKeyError: t("incorrectApiKey", { ns: "config" }),
invalidApiKeyError: t("invalidApiKeyError", { ns: "config" }),
},
publish
))
) {
setChangeOpenAiApiKeyRequestPending(false);

return;
}

await updateUserIdentity({
openai_api_key: openAiApiKey,
});
Expand Down
6 changes: 4 additions & 2 deletions frontend/public/locales/en/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,7 @@
"roleRequired": "You don't have the necessary role to access this tab 🧠💡🥲.",
"requireAccess": "Please require access from the owner.",
"ohno": "Oh no!",
"noUser": "No user"
}
"noUser": "No user",
"incorrectApiKey": "Incorrect API Key",
"invalidApiKeyError": "Invalid API Key"
}

0 comments on commit 93b3fb3

Please sign in to comment.