Ewan Claude commited on
Commit
712a4b7
·
1 Parent(s): 1b03072

Fix app to handle missing API key gracefully

Browse files

- Implemented lazy initialization of conversation chain
- Added helpful error messages when API key is not set
- App now starts successfully even without API key configured
- Shows warning in UI when API key is missing

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (1) hide show
  1. app.py +28 -7
app.py CHANGED
@@ -20,22 +20,22 @@ def get_session_history(session_id: str):
20
  def create_chain():
21
  groq_api_key = os.getenv("GROQ_API_KEY")
22
  if not groq_api_key:
23
- raise ValueError("GROQ_API_KEY environment variable is not set")
24
-
25
  llm = ChatGroq(
26
  model="openai/gpt-oss-20b",
27
  temperature=0.7,
28
  max_retries=2,
29
  )
30
-
31
  prompt = ChatPromptTemplate.from_messages([
32
  ("system", "You are a helpful AI assistant. Be concise and helpful."),
33
  MessagesPlaceholder(variable_name="history"),
34
  ("human", "{input}"),
35
  ])
36
-
37
  chain = prompt | llm
38
-
39
  return RunnableWithMessageHistory(
40
  chain,
41
  get_session_history,
@@ -43,9 +43,26 @@ def create_chain():
43
  history_messages_key="history",
44
  )
45
 
46
- conversation_chain = create_chain()
 
47
 
48
  def chat(message, history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  try:
50
  response = conversation_chain.invoke(
51
  {"input": message},
@@ -61,7 +78,11 @@ def chat(message, history):
61
  with gr.Blocks(title="LangChain Groq Chat Demo") as demo:
62
  gr.Markdown("# LangChain + Groq Chat Demo")
63
  gr.Markdown("Chat with OpenAI's GPT-OSS-20B model using LangChain v1")
64
-
 
 
 
 
65
  chatbot = gr.Chatbot(height=400)
66
  msg = gr.Textbox(
67
  placeholder="Type your message here...",
 
20
  def create_chain():
21
  groq_api_key = os.getenv("GROQ_API_KEY")
22
  if not groq_api_key:
23
+ return None
24
+
25
  llm = ChatGroq(
26
  model="openai/gpt-oss-20b",
27
  temperature=0.7,
28
  max_retries=2,
29
  )
30
+
31
  prompt = ChatPromptTemplate.from_messages([
32
  ("system", "You are a helpful AI assistant. Be concise and helpful."),
33
  MessagesPlaceholder(variable_name="history"),
34
  ("human", "{input}"),
35
  ])
36
+
37
  chain = prompt | llm
38
+
39
  return RunnableWithMessageHistory(
40
  chain,
41
  get_session_history,
 
43
  history_messages_key="history",
44
  )
45
 
46
+ # Lazy initialization - chain will be created on first use
47
+ conversation_chain = None
48
 
49
  def chat(message, history):
50
+ global conversation_chain
51
+
52
+ # Check if API key is set
53
+ if not os.getenv("GROQ_API_KEY"):
54
+ error_msg = "⚠️ GROQ_API_KEY is not set. Please add it in the Space settings under 'Variables and secrets'."
55
+ history.append([message, error_msg])
56
+ return "", history
57
+
58
+ # Create chain on first use
59
+ if conversation_chain is None:
60
+ conversation_chain = create_chain()
61
+ if conversation_chain is None:
62
+ error_msg = "⚠️ Failed to initialize the chat model. Please check the API key."
63
+ history.append([message, error_msg])
64
+ return "", history
65
+
66
  try:
67
  response = conversation_chain.invoke(
68
  {"input": message},
 
78
  with gr.Blocks(title="LangChain Groq Chat Demo") as demo:
79
  gr.Markdown("# LangChain + Groq Chat Demo")
80
  gr.Markdown("Chat with OpenAI's GPT-OSS-20B model using LangChain v1")
81
+
82
+ # Show API key status
83
+ if not os.getenv("GROQ_API_KEY"):
84
+ gr.Markdown("⚠️ **Note:** GROQ_API_KEY is not configured. Please add it in Space settings to use this app.")
85
+
86
  chatbot = gr.Chatbot(height=400)
87
  msg = gr.Textbox(
88
  placeholder="Type your message here...",