HedronCreeper commited on
Commit
6f3d9b8
·
verified ·
1 Parent(s): 4b7bbcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -19
app.py CHANGED
@@ -1,51 +1,61 @@
1
  import os
 
2
  import gradio as gr
3
- from openai import OpenAI
4
 
5
  # Fetch the API key from Hugging Face Spaces Secrets
6
  OPENROUTER_API_KEY = os.environ.get("API_KEY")
7
 
8
- # Initialize OpenAI client targeting OpenRouter
9
- client = OpenAI(
10
  base_url="https://openrouter.ai",
11
  api_key=OPENROUTER_API_KEY,
12
  )
13
 
14
- def predict(message, history):
 
15
  if not OPENROUTER_API_KEY:
16
  yield "Error: API_KEY secret is missing in Hugging Face Space settings."
17
  return
18
 
19
- # In modern Gradio versions, 'history' is natively a list of dicts.
20
- # Copy existing history and append the latest user entry.
21
- messages = list(history) if history else []
22
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
 
 
 
23
 
24
  try:
25
- # Call the OpenRouter API stream
26
- response = client.chat.completions.create(
27
  model="meta-llama/llama-3-8b-instruct:free",
28
- messages=messages,
29
  stream=True
30
  )
31
 
32
- # Yield chunks for a smooth, streaming typing effect
33
  partial_message = ""
34
- for chunk in response:
35
- if chunk.choices and chunk.choices.delta.content:
36
- partial_message += chunk.choices.delta.content
37
  yield partial_message
38
 
39
  except Exception as e:
40
- yield f"An error occurred: {str(e)}"
41
 
42
- # Define the ChatInterface cleanly for Gradio's newest standard
43
  demo = gr.ChatInterface(
44
  fn=predict,
45
  title="OpenRouter Chatbot",
46
- description="Running seamlessly on the absolute latest version of Gradio.",
47
  )
48
 
49
  if __name__ == "__main__":
50
- # Disable experimental SSR mode to prevent 404 heartbeat connection errors
51
  demo.launch(ssr_mode=False)
 
1
  import os
2
+ import asyncio
3
  import gradio as gr
4
+ from openai import AsyncOpenAI
5
 
6
  # Fetch the API key from Hugging Face Spaces Secrets
7
  OPENROUTER_API_KEY = os.environ.get("API_KEY")
8
 
9
+ # Initialize the ASYNC client targeting OpenRouter
10
+ client = AsyncOpenAI(
11
  base_url="https://openrouter.ai",
12
  api_key=OPENROUTER_API_KEY,
13
  )
14
 
15
+ # Using 'async def' properly handles streaming under Python 3.13
16
+ async def predict(message, history):
17
  if not OPENROUTER_API_KEY:
18
  yield "Error: API_KEY secret is missing in Hugging Face Space settings."
19
  return
20
 
21
+ # Clean up history: Modern Gradio can include system blocks or objects.
22
+ # OpenRouter requires only raw 'user' and 'assistant' text roles.
23
+ cleaned_messages = []
24
+ if history:
25
+ for msg in history:
26
+ role = msg.get("role")
27
+ content = msg.get("content")
28
+ # Only append standard text conversations
29
+ if role in ["user", "assistant"] and isinstance(content, str):
30
+ cleaned_messages.append({"role": role, "content": content})
31
+
32
+ # Append the new user prompt
33
+ cleaned_messages.append({"role": "user", "content": message})
34
 
35
  try:
36
+ # Request an async stream from OpenRouter
37
+ response = await client.chat.completions.create(
38
  model="meta-llama/llama-3-8b-instruct:free",
39
+ messages=cleaned_messages,
40
  stream=True
41
  )
42
 
43
+ # Async generator prevents the StopAsyncIteration crash entirely
44
  partial_message = ""
45
+ async for chunk in response:
46
+ if chunk.choices and chunk.choices[0].delta.content:
47
+ partial_message += chunk.choices[0].delta.content
48
  yield partial_message
49
 
50
  except Exception as e:
51
+ yield f"An error occurred while connecting to OpenRouter: {str(e)}"
52
 
53
+ # Define the ChatInterface cleanly
54
  demo = gr.ChatInterface(
55
  fn=predict,
56
  title="OpenRouter Chatbot",
57
+ description="Running safely on the absolute latest version of Gradio and Python 3.13.",
58
  )
59
 
60
  if __name__ == "__main__":
 
61
  demo.launch(ssr_mode=False)