Skip to content

Commit 9cf92a2

Browse files
committed
fix: openai api key optionality for chat playground
1 parent 867d757 commit 9cf92a2

File tree

5 files changed

+63
-7
lines changed

5 files changed

+63
-7
lines changed

Diff for: backend/app/api/v1/endpoints/chat.py

+15
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,26 @@
99
from app import crud, schemas
1010
from app.api.deps import get_db, get_user
1111
from app.core.chat_service import chat_service
12+
from app.core.config import settings
1213
from app.core.logging import logger
1314

1415
router = APIRouter()
1516

1617

18+
@router.get("/openai_key_set", response_model=bool)
19+
async def openai_key_set(
20+
*,
21+
db: AsyncSession = Depends(get_db),
22+
user: schemas.User = Depends(get_user),
23+
) -> bool:
24+
"""Check if the OpenAI API key is set for the current user.
25+
26+
Returns:
27+
bool: True if the OpenAI API key is set, False otherwise.
28+
"""
29+
return settings.OPENAI_API_KEY is not None
30+
31+
1732
@router.post("/", response_model=schemas.Chat)
1833
async def create_chat(
1934
*,

Diff for: backend/app/core/chat_service.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -50,11 +50,12 @@ class ChatService:
5050
def __init__(self):
5151
"""Initialize the chat service with OpenAI client."""
5252
if not settings.OPENAI_API_KEY:
53-
raise ValueError("OPENAI_API_KEY must be set in environment variables")
54-
55-
self.client = AsyncOpenAI(
56-
api_key=settings.OPENAI_API_KEY,
57-
)
53+
logger.warning("OPENAI_API_KEY is not set in environment variables")
54+
self.client = None
55+
else:
56+
self.client = AsyncOpenAI(
57+
api_key=settings.OPENAI_API_KEY,
58+
)
5859

5960
async def generate_streaming_response(
6061
self,

Diff for: backend/app/core/config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ class Settings(BaseSettings):
5858
NATIVE_WEAVIATE_PORT: int = 8080
5959
NATIVE_WEAVIATE_GRPC_PORT: int = 50051
6060

61-
OPENAI_API_KEY: str
61+
OPENAI_API_KEY: Optional[str] = None
6262

6363
@field_validator("SQLALCHEMY_ASYNC_DATABASE_URI", mode="before")
6464
def assemble_db_connection(cls, v: Optional[str], info: ValidationInfo) -> PostgresDsn:

Diff for: frontend/src/components/DashboardLayout.tsx

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ const DashboardLayout = () => {
4242
icon: LayoutDashboard,
4343
},
4444
{
45-
name: "Chat",
45+
name: "Chat playground",
4646
href: "/chat",
4747
icon: MessageSquare,
4848
},

Diff for: frontend/src/pages/Chat.tsx

+40
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
2121
import { CreateChatDialog } from "@/components/chat/CreateChatDialog";
2222
import { Spinner } from "@/components/ui/spinner";
2323
import { cn } from "@/lib/utils";
24+
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
2425

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

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

311+
// Add this effect at the top of other effects
312+
useEffect(() => {
313+
async function checkOpenAIKey() {
314+
try {
315+
const response = await apiClient.get('/chat/openai_key_set');
316+
const isSet = await response.json();
317+
setIsOpenAIKeySet(isSet);
318+
} catch (error) {
319+
console.error("Failed to check OpenAI key:", error);
320+
setIsOpenAIKeySet(false);
321+
}
322+
}
323+
324+
void checkOpenAIKey();
325+
}, []);
326+
327+
// Add this dialog component before the main return
328+
if (isOpenAIKeySet === false) {
329+
return (
330+
<Dialog
331+
open={true}
332+
onOpenChange={() => navigate('/dashboard')}
333+
>
334+
<DialogContent onEscapeKeyDown={() => navigate('/dashboard')} onInteractOutside={() => navigate('/dashboard')}>
335+
<DialogHeader>
336+
<DialogTitle>OpenAI API key required</DialogTitle>
337+
<DialogDescription>
338+
Please add your OpenAI API key to the .env file to continue using the chat functionality.
339+
<br />
340+
<br />
341+
Find the .env file in the root of the project and add the following: OPENAI_API_KEY=your_openai_api_key
342+
</DialogDescription>
343+
</DialogHeader>
344+
</DialogContent>
345+
</Dialog>
346+
);
347+
}
348+
309349
return (
310350
<div className="flex h-full">
311351
<ChatSidebar onCreateChat={() => setShowCreateDialog(true)} />

0 commit comments

Comments
 (0)