Skip to content

Commit

Permalink
fix: openai api key optionality for chat playground
Browse files Browse the repository at this point in the history
  • Loading branch information
orhanrauf committed Feb 4, 2025
1 parent 867d757 commit 9cf92a2
Show file tree
Hide file tree
Showing 5 changed files with 63 additions and 7 deletions.
15 changes: 15 additions & 0 deletions backend/app/api/v1/endpoints/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,26 @@
from app import crud, schemas
from app.api.deps import get_db, get_user
from app.core.chat_service import chat_service
from app.core.config import settings
from app.core.logging import logger

router = APIRouter()


@router.get("/openai_key_set", response_model=bool)
async def openai_key_set(
*,
db: AsyncSession = Depends(get_db),
user: schemas.User = Depends(get_user),
) -> bool:
"""Check if the OpenAI API key is set for the current user.
Returns:
bool: True if the OpenAI API key is set, False otherwise.
"""
return settings.OPENAI_API_KEY is not None


@router.post("/", response_model=schemas.Chat)
async def create_chat(
*,
Expand Down
11 changes: 6 additions & 5 deletions backend/app/core/chat_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,12 @@ class ChatService:
def __init__(self):
"""Initialize the chat service with OpenAI client."""
if not settings.OPENAI_API_KEY:
raise ValueError("OPENAI_API_KEY must be set in environment variables")

self.client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY,
)
logger.warning("OPENAI_API_KEY is not set in environment variables")
self.client = None
else:
self.client = AsyncOpenAI(
api_key=settings.OPENAI_API_KEY,
)

async def generate_streaming_response(
self,
Expand Down
2 changes: 1 addition & 1 deletion backend/app/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Settings(BaseSettings):
NATIVE_WEAVIATE_PORT: int = 8080
NATIVE_WEAVIATE_GRPC_PORT: int = 50051

OPENAI_API_KEY: str
OPENAI_API_KEY: Optional[str] = None

@field_validator("SQLALCHEMY_ASYNC_DATABASE_URI", mode="before")
def assemble_db_connection(cls, v: Optional[str], info: ValidationInfo) -> PostgresDsn:
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/DashboardLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const DashboardLayout = () => {
icon: LayoutDashboard,
},
{
name: "Chat",
name: "Chat playground",
href: "/chat",
icon: MessageSquare,
},
Expand Down
40 changes: 40 additions & 0 deletions frontend/src/pages/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
import { CreateChatDialog } from "@/components/chat/CreateChatDialog";
import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";

interface Message {
role: "user" | "assistant";
Expand All @@ -39,6 +40,7 @@ function Chat() {
const navigate = useNavigate();
const [chatInfo, setChatInfo] = useState<ChatInfo | null>(null);
const [showCreateDialog, setShowCreateDialog] = useState(false);
const [isOpenAIKeySet, setIsOpenAIKeySet] = useState<boolean | null>(null);

// If you're using a route param like /chat/:chatId
const { chatId } = useParams<{ chatId: string }>();
Expand Down Expand Up @@ -306,6 +308,44 @@ function Chat() {
}
}, [location.state]);

// Add this effect at the top of other effects
useEffect(() => {
async function checkOpenAIKey() {
try {
const response = await apiClient.get('/chat/openai_key_set');
const isSet = await response.json();
setIsOpenAIKeySet(isSet);
} catch (error) {
console.error("Failed to check OpenAI key:", error);
setIsOpenAIKeySet(false);
}
}

void checkOpenAIKey();
}, []);

// Add this dialog component before the main return
if (isOpenAIKeySet === false) {
return (
<Dialog
open={true}
onOpenChange={() => navigate('/dashboard')}
>
<DialogContent onEscapeKeyDown={() => navigate('/dashboard')} onInteractOutside={() => navigate('/dashboard')}>
<DialogHeader>
<DialogTitle>OpenAI API key required</DialogTitle>
<DialogDescription>
Please add your OpenAI API key to the .env file to continue using the chat functionality.
<br />
<br />
Find the .env file in the root of the project and add the following: OPENAI_API_KEY=your_openai_api_key
</DialogDescription>
</DialogHeader>
</DialogContent>
</Dialog>
);
}

return (
<div className="flex h-full">
<ChatSidebar onCreateChat={() => setShowCreateDialog(true)} />
Expand Down

0 comments on commit 9cf92a2

Please sign in to comment.