BotXT commited on
Commit
409c9d0
·
verified ·
1 Parent(s): 7817e26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -16
app.py CHANGED
@@ -2,9 +2,8 @@ import os
2
  from openai import OpenAI
3
  from shiny import App, render, ui, reactive
4
 
5
- # Clean, error-free layout framework
6
  app_ui = ui.page_fluid(
7
- ui.h2("NexusAI Assistant"),
8
  ui.hr(),
9
  ui.input_text_area("user_prompt", "Enter your prompt below:", "What is the meaning of life?"),
10
  ui.input_action_button("submit_btn", "Send Query"),
@@ -15,51 +14,63 @@ app_ui = ui.page_fluid(
15
 
16
  def server(input, output, session):
17
 
18
- # Asynchronous background thread to manage the network waiting time
19
  @reactive.extended_task
20
  async def fetch_ai_response(prompt_text):
21
  try:
 
 
 
 
 
 
22
  client = OpenAI(
23
- base_url="https://openrouter.ai",
24
- api_key=os.environ.get("OPENROUTER_API_KEY"),
25
  )
26
 
 
27
  completion = client.chat.completions.create(
28
  extra_headers={
29
  "HTTP-Referer": "https://huggingface.co",
30
  "X-OpenRouter-Title": "NexusAI Shiny Dashboard",
31
  },
32
- model="poolside/laguna-xs.2:free",
33
  messages=[{"role": "user", "content": prompt_text}]
34
  )
35
 
36
- # CORE FIX: Added [0] to extract the text from the first choice object array index
37
- ai_text = completion.choices[0].message.content
38
- return {"status": "success", "content": ai_text}
39
-
 
 
 
40
  except Exception as e:
41
- return {"status": "error", "content": str(e)}
 
42
 
43
- # Listen for button triggers
44
  @reactive.effect
45
  @reactive.event(input.submit_btn)
46
  def _():
47
  fetch_ai_response.trigger(input.user_prompt())
48
 
49
- # Safely swap display states without causing the web browser to hang
50
  @render.ui
51
  def ai_display_area():
52
  if fetch_ai_response.status() == "initial":
53
  return ui.p("System idle. Awaiting user input...")
54
 
55
  elif fetch_ai_response.status() == "running":
56
- return ui.p("Analyzing sequence structures... Please wait.")
57
 
58
  elif fetch_ai_response.status() == "result":
59
  res = fetch_ai_response.result()
60
  if res["status"] == "success":
61
  return ui.markdown(res["content"])
62
  else:
63
- return ui.p(f"Connection Error: {res['content']}")
 
 
 
 
64
 
65
- app = App(app_ui, server)
 
2
  from openai import OpenAI
3
  from shiny import App, render, ui, reactive
4
 
 
5
  app_ui = ui.page_fluid(
6
+ ui.h2("NexusAI Assistant (Debug Mode)"),
7
  ui.hr(),
8
  ui.input_text_area("user_prompt", "Enter your prompt below:", "What is the meaning of life?"),
9
  ui.input_action_button("submit_btn", "Send Query"),
 
14
 
15
  def server(input, output, session):
16
 
 
17
  @reactive.extended_task
18
  async def fetch_ai_response(prompt_text):
19
  try:
20
+ # 1. Verify Hugging Face has access to your secret key configuration
21
+ api_key = os.environ.get("OPENROUTER_API_KEY")
22
+ if not api_key:
23
+ return {"status": "error", "content": "HF_SECRET_MISSING: Your OPENROUTER_API_KEY was not found in your Hugging Face Space Settings. Please check your Settings tab."}
24
+
25
+ # 2. Initialize connection
26
  client = OpenAI(
27
+ base_url="https://openrouter.ai/api/v1",
28
+ api_key=api_key,
29
  )
30
 
31
+ # 3. Call Poolside Laguna XS.2
32
  completion = client.chat.completions.create(
33
  extra_headers={
34
  "HTTP-Referer": "https://huggingface.co",
35
  "X-OpenRouter-Title": "NexusAI Shiny Dashboard",
36
  },
37
+ model="poolside/laguna-xs.2:free",
38
  messages=[{"role": "user", "content": prompt_text}]
39
  )
40
 
41
+ # 4. Safely extract message from array index to prevent silent background freezing
42
+ if completion and hasattr(completion, 'choices') and len(completion.choices) > 0:
43
+ ai_text = completion.choices[0].message.content
44
+ return {"status": "success", "content": ai_text}
45
+ else:
46
+ return {"status": "error", "content": f"EMPTY_RESPONSE: OpenRouter payload did not contain choices. Raw data: {str(completion)}"}
47
+
48
  except Exception as e:
49
+ # Captures any network timeout or key authentication issues directly
50
+ return {"status": "error", "content": f"API_EXCEPTION: {str(e)}"}
51
 
 
52
  @reactive.effect
53
  @reactive.event(input.submit_btn)
54
  def _():
55
  fetch_ai_response.trigger(input.user_prompt())
56
 
 
57
  @render.ui
58
  def ai_display_area():
59
  if fetch_ai_response.status() == "initial":
60
  return ui.p("System idle. Awaiting user input...")
61
 
62
  elif fetch_ai_response.status() == "running":
63
+ return ui.p("Connecting to OpenRouter and calling poolside/laguna-xs.2:free... Please wait.")
64
 
65
  elif fetch_ai_response.status() == "result":
66
  res = fetch_ai_response.result()
67
  if res["status"] == "success":
68
  return ui.markdown(res["content"])
69
  else:
70
+ # Displays explicit errors on-screen instead of hanging
71
+ return ui.div(
72
+ ui.h5("System Stopped", style="color: red;"),
73
+ ui.p(res["content"], style="font-family: monospace; background-color: #ffe6e6; padding: 10px; border-radius: 5px; color: black;"),
74
+ )
75
 
76
+ app = App(app_ui, server)