SaisExperiments commited on
Commit
f311bae
·
verified ·
1 Parent(s): c137ca3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -106
app.py CHANGED
@@ -1,134 +1,64 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
- # Import the correct exception class
4
- from huggingface_hub.utils import HfHubHTTPError
5
- import os
6
 
7
  """
8
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
9
-
10
- **Note:** You might need to authenticate with Hugging Face for this to work reliably.
11
- Run `huggingface-cli login` in your terminal or set the HUGGING_FACE_HUB_TOKEN environment variable.
12
- Alternatively, pass your token directly: InferenceClient(token="hf_YOUR_TOKEN")
13
  """
14
- # Initialize the Inference Client
15
- # It will try to use HUGGING_FACE_HUB_TOKEN environment variable or cached login
16
- try:
17
- # You might need to provide a token if you haven't logged in via CLI
18
- # token = os.getenv("HUGGING_FACE_HUB_TOKEN")
19
- # client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=token)
20
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
21
- except Exception as e:
22
- print(f"Error initializing InferenceClient: {e}")
23
- raise ValueError("Could not initialize InferenceClient. Ensure you are logged in or provide a token.") from e
24
 
25
 
26
  def respond(
27
- message: str,
28
- history: list[tuple[str | None, str | None]],
29
- system_message: str,
30
- max_tokens: int,
31
- temperature: float,
32
- top_p: float,
33
  ):
34
- """
35
- Generates a response using the Hugging Face Inference API.
36
-
37
- Args:
38
- message: The user's input message.
39
- history: A list of tuples representing the conversation history.
40
- Each tuple is (user_message, bot_message).
41
- system_message: The system prompt to guide the model.
42
- max_tokens: The maximum number of new tokens to generate.
43
- temperature: Controls randomness (higher = more random).
44
- top_p: Nucleus sampling parameter.
45
-
46
- Yields:
47
- The generated response incrementally.
48
- """
49
  messages = [{"role": "system", "content": system_message}]
50
 
51
- # Add conversation history
52
- for user_msg, bot_msg in history:
53
  if user_msg:
54
  messages.append({"role": "user", "content": user_msg})
55
- if bot_msg:
56
- messages.append({"role": "assistant", "content": bot_msg})
57
 
58
- # Add the latest user message
59
  messages.append({"role": "user", "content": message})
60
 
61
  response = ""
62
- try:
63
- # Start streaming the response
64
- for msg_chunk in client.chat_completion(
65
- messages=messages,
66
- max_tokens=max_tokens,
67
- stream=True,
68
- temperature=temperature,
69
- top_p=top_p,
70
- ):
71
- # Check if there's content in the delta
72
- token = msg_chunk.choices[0].delta.content
73
- if token: # Add check for empty/None token
74
- response += token
75
- yield response # Yield the accumulated response so far
76
-
77
- # Catch HTTP errors from the Hugging Face Hub API
78
- except HfHubHTTPError as e:
79
- error_message = f"Inference API Error: {e}"
80
- # Try to get more details from the response if available
81
- if e.response:
82
- try:
83
- details = e.response.json()
84
- error_message += f"\nDetails: {details.get('error', 'N/A')}"
85
- except Exception: # Catch potential JSON decoding errors
86
- pass # Keep the original error message
87
- print(error_message)
88
- yield f"Sorry, I encountered an error communicating with the model service: {e}" # Display a user-friendly message
89
 
90
- # Catch other potential errors
91
- except Exception as e:
92
- print(f"An unexpected error occurred: {e}")
93
- yield f"Sorry, an unexpected error occurred: {e}"
 
 
 
 
 
 
94
 
95
 
96
  """
97
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
98
  """
99
- demo = gr.ChatInterface(
100
- respond,
101
- chatbot=gr.Chatbot(height=400), # Adjust chatbot height if desired
102
- textbox=gr.Textbox(placeholder="Ask me anything...", container=False, scale=7),
103
- title="Zephyr 7B Beta Chat",
104
- description="Chat with the Zephyr 7B Beta model using the Hugging Face Inference API.",
105
- theme="soft", # Optional: Apply a theme
106
- examples=[
107
- ["Hello!"],
108
- ["Explain the concept of Large Language Models in simple terms."],
109
- ["Write a short poem about the moon."],
110
- ],
111
- cache_examples=False, # Set to True to cache example results
112
- retry_btn="Retry",
113
- undo_btn="Undo",
114
- clear_btn="Clear",
115
- additional_inputs=[
116
- gr.Textbox(value="You are a friendly and helpful chatbot.", label="System message"),
117
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
118
- gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature"), # Note: Max temp often capped lower (e.g., 1.0 or 2.0)
119
- gr.Slider(
120
- minimum=0.1,
121
- maximum=1.0,
122
- value=0.95,
123
- step=0.05,
124
- label="Top-p (nucleus sampling)",
125
- ),
126
- ],
127
- additional_inputs_accordion=gr.Accordion(label="Advanced Options", open=False), # Group additional inputs
128
- )
129
 
130
 
131
  if __name__ == "__main__":
132
- # Ensure huggingface_hub library is up-to-date: pip install --upgrade huggingface_hub
133
- print("Launching Gradio Interface...")
134
  demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
 
3
 
4
  """
5
  For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
 
 
 
 
6
  """
7
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
 
 
 
 
 
 
 
 
8
 
9
 
10
  def respond(
11
+ message,
12
+ history: list[tuple[str, str]],
13
+ system_message,
14
+ max_tokens,
15
+ temperature,
16
+ top_p,
17
  ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  messages = [{"role": "system", "content": system_message}]
19
 
20
+ for user_msg, assistant_msg in history:
 
21
  if user_msg:
22
  messages.append({"role": "user", "content": user_msg})
23
+ if assistant_msg:
24
+ messages.append({"role": "assistant", "content": assistant_msg})
25
 
 
26
  messages.append({"role": "user", "content": message})
27
 
28
  response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ for event in client.chat_completion(
31
+ messages,
32
+ max_tokens=int(max_tokens),
33
+ stream=True,
34
+ temperature=temperature,
35
+ top_p=top_p,
36
+ ):
37
+ if event.token is not None:
38
+ response += event.token
39
+ yield response
40
 
41
 
42
  """
43
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
  """
45
+ with gr.Blocks() as demo:
46
+ chatbot = gr.ChatInterface(
47
+ respond,
48
+ additional_inputs=[
49
+ gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
+ gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
+ gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
+ gr.Slider(
53
+ minimum=0.1,
54
+ maximum=1.0,
55
+ value=0.95,
56
+ step=0.05,
57
+ label="Top-p (nucleus sampling)",
58
+ ),
59
+ ],
60
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
 
63
  if __name__ == "__main__":
 
 
64
  demo.launch()