Files changed (3) hide show
  1. app.py +51 -76
  2. custom.css +0 -13
  3. requirements.txt +1 -2
app.py CHANGED
@@ -1,89 +1,64 @@
1
- # βœ… Imports
2
- from openai import OpenAI
3
  import gradio as gr
4
- import os
5
 
6
- # βœ… Load API key from Hugging Face Secrets (environment variables)
7
- api_key = os.getenv("OPENROUTER_API_KEY")
8
- if not api_key:
9
- raise ValueError("⚠️ OPENROUTER_API_KEY not found. Add it in HF Spaces > Settings > Secrets.")
10
-
11
- # βœ… OpenRouter API client setup
12
- client = OpenAI(
13
- base_url="https://openrouter.ai/api/v1",
14
- api_key=api_key,
15
- )
16
-
17
- # βœ… Chat function using Kimi-K2
18
- def ask_kimi(prompt, history=None):
19
- if history is None:
20
- history = []
21
-
22
- messages = [{"role": "system", "content": "Wewe ni msaidizi mzuri wa kujifunza programu kwa Kiswahili."}]
23
- for user, bot in history:
24
- messages.append({"role": "user", "content": user})
25
- messages.append({"role": "assistant", "content": bot})
26
- messages.append({"role": "user", "content": prompt})
27
 
28
- completion = client.chat.completions.create(
29
- model="moonshotai/kimi-k2:free",
30
- messages=messages,
31
- extra_headers={
32
- "HTTP-Referer": "https://your-site.com",
33
- "X-Title": "NextDev Academy",
34
- }
35
- )
36
 
37
- reply = completion.choices[0].message.content
38
- history.append((prompt, reply))
39
- return reply, history
 
 
 
 
 
 
40
 
41
- # βœ… Optional inline CSS
42
- custom_css = """
43
- <style>
44
- body {
45
- background-color: #f9f9f9;
46
- }
47
- .gradio-container {
48
- max-width: 700px;
49
- margin: auto;
50
- }
51
- .gradio-chatbot {
52
- background-color: #eef2f7;
53
- border-radius: 10px;
54
- padding: 10px;
55
- }
56
- </style>
57
- """
58
 
59
- # βœ… Gradio UI with proper layout and "messages" type
60
- with gr.Blocks() as demo:
61
- gr.HTML(custom_css) # Inject custom styles
62
- gr.Markdown("## πŸ€– Kimi K2 Chatbot kwa Kiswahili (Powered by OpenRouter)")
63
 
64
- chatbot = gr.Chatbot(label="Kimi K2", type="messages")
65
- state = gr.State([])
66
 
67
- with gr.Row():
68
- msg = gr.Textbox(
69
- placeholder="Uliza swali kuhusu programu au teknolojia...",
70
- show_label=False,
71
- scale=4
72
- )
73
- submit = gr.Button("➑️ Tuma", scale=1)
 
74
 
75
- clear = gr.Button("πŸ”„ Anza upya")
 
76
 
77
- # Chat submission logic - return updated chat history and clear input box
78
- def user_submit(user_message, history):
79
- response, updated_history = ask_kimi(user_message, history)
80
- return updated_history, updated_history, ""
81
 
82
- # Bind submit with Enter or button click
83
- msg.submit(user_submit, [msg, state], [chatbot, state, msg])
84
- submit.click(user_submit, [msg, state], [chatbot, state, msg])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
- clear.click(lambda: ([], [], ""), None, [chatbot, state, msg])
87
 
88
- # βœ… Launch the app (do NOT use css= arg here)
89
- 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 val in history:
21
+ if val[0]:
22
+ messages.append({"role": "user", "content": val[0]})
23
+ if val[1]:
24
+ messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
 
 
 
25
 
26
+ messages.append({"role": "user", "content": message})
 
 
 
27
 
28
+ response = ""
 
29
 
30
+ for message in client.chat_completion(
31
+ messages,
32
+ max_tokens=max_tokens,
33
+ stream=True,
34
+ temperature=temperature,
35
+ top_p=top_p,
36
+ ):
37
+ token = message.choices[0].delta.content
38
 
39
+ response += token
40
+ yield response
41
 
 
 
 
 
42
 
43
+ """
44
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
+ """
46
+ demo = 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()
custom.css DELETED
@@ -1,13 +0,0 @@
1
- /* Hide Gradio footer branding */
2
- footer {
3
- display: none !important;
4
- }
5
-
6
- /* Optional: Custom header */
7
- .gradio-container::before {
8
- content: "NextDev Academy Chatbot";
9
- display: block;
10
- font-size: 1.5rem;
11
- font-weight: bold;
12
- margin: 10px;
13
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,2 +1 @@
1
- gradio
2
- openai
 
1
+ huggingface_hub==0.25.2