chthees commited on
Commit
5b2c980
·
verified ·
1 Parent(s): 1d5858a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -44
app.py CHANGED
@@ -1,6 +1,45 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
@@ -10,61 +49,61 @@ def respond(
10
  temperature,
11
  top_p,
12
  hf_token: gr.OAuthToken,
 
13
  ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
20
 
21
- messages.extend(history)
 
 
 
 
 
 
22
 
 
 
23
  messages.append({"role": "user", "content": message})
24
 
25
  response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
  ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
 
63
  with gr.Blocks() as demo:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  with gr.Sidebar():
65
  gr.LoginButton()
66
- chatbot.render()
67
-
68
 
69
  if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import requests
4
 
5
+ # Funktion, um Kontext von Wikipedia zu holen
6
+ def get_wikipedia_summary(query):
7
+ try:
8
+ # Wir nutzen die öffentliche Wikipedia API
9
+ response = requests.get(
10
+ "https://de.wikipedia.org/w/api.php",
11
+ params={
12
+ "action": "query",
13
+ "format": "json",
14
+ "list": "search",
15
+ "srsearch": query,
16
+ "srlimit": 1
17
+ }
18
+ ).json()
19
+
20
+ if not response["query"]["search"]:
21
+ return None
22
+
23
+ page_id = response["query"]["search"][0]["pageid"]
24
+
25
+ # Details zur Seite holen
26
+ details = requests.get(
27
+ "https://de.wikipedia.org/w/api.php",
28
+ params={
29
+ "action": "query",
30
+ "format": "json",
31
+ "prop": "extracts",
32
+ "pageids": page_id,
33
+ "explaintext": True,
34
+ "exintro": True,
35
+ "exsentences": 7 # Nur die ersten 7 Sätze
36
+ }
37
+ ).json()
38
+
39
+ page = details["query"]["pages"][str(page_id)]
40
+ return page["extract"]
41
+ except Exception as e:
42
+ return None
43
 
44
  def respond(
45
  message,
 
49
  temperature,
50
  top_p,
51
  hf_token: gr.OAuthToken,
52
+ use_wiki # Checkbox Input
53
  ):
54
+ client = InferenceClient(token=hf_token.token, model="meta-llama/Llama-3.2-1B-Instruct")
 
 
 
55
 
56
+ # --- HIER PASSIERT DAS IN-CONTEXT LEARNING ---
57
+ context_text = ""
58
+ if use_wiki:
59
+ wiki_content = get_wikipedia_summary(message)
60
+ if wiki_content:
61
+ context_text = f"\n\nEXTERNER KONTEXT (WIKIPEDIA): {wiki_content}\n"
62
+ gr.Info(f"Kontext gefunden: {wiki_content[:50]}...") # Kleines UI Feedback
63
+ else:
64
+ gr.Info("Kein Wikipedia-Artikel gefunden.")
65
 
66
+ # Der Prompt zwingt das Modell, den Kontext zu nutzen
67
+ final_system_prompt = (
68
+ f"{system_message} "
69
+ f"Wenn 'EXTERNER KONTEXT' bereitgestellt wird, nutze dieses Wissen, um die Frage zu beantworten. "
70
+ f"Verlasse dich mehr auf den Kontext als auf dein eigenes Wissen."
71
+ f"{context_text}"
72
+ )
73
 
74
+ messages = [{"role": "system", "content": final_system_prompt}]
75
+ messages.extend(history)
76
  messages.append({"role": "user", "content": message})
77
 
78
  response = ""
79
+ for msg in client.chat_completion(
80
+ messages, max_tokens=max_tokens, stream=True, temperature=temperature, top_p=top_p,
 
 
 
 
 
81
  ):
82
+ token = msg.choices[0].delta.content
83
+ if token:
84
+ response += token
85
+ yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
+ # --- GUI ---
88
  with gr.Blocks() as demo:
89
+ gr.Markdown("# 🧠 Der Wikipedia-gestützte Assistent")
90
+ gr.Markdown("Stelle eine Frage. Wenn du die Checkbox aktivierst, suche ich live nach Fakten!")
91
+
92
+ with gr.Row():
93
+ wiki_checkbox = gr.Checkbox(label="Nutze Wikipedia-Wissen (RAG)", value=True)
94
+
95
+ chatbot = gr.ChatInterface(
96
+ respond,
97
+ additional_inputs=[
98
+ gr.Textbox(value="Du bist ein hilfreicher Assistent der Dinge genau und exakt erklärt.", label="System"),
99
+ gr.Slider(1, 1024, 512, label="Max Tokens"),
100
+ gr.Slider(0.1, 2.0, 0.7, label="Temp"),
101
+ gr.Slider(0.1, 1.0, 0.95, label="Top-p"),
102
+ wiki_checkbox
103
+ ]
104
+ )
105
  with gr.Sidebar():
106
  gr.LoginButton()
 
 
107
 
108
  if __name__ == "__main__":
109
+ demo.launch()