Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def ask_openrouter(input_text, history):
|
|
|
|
| 2 |
key = os.getenv("OPENROUTER_API_KEY", "").strip()
|
| 3 |
if not key:
|
| 4 |
-
raise gr.Error(
|
|
|
|
|
|
|
| 5 |
|
| 6 |
input_text = (input_text or "").strip()
|
| 7 |
if not input_text:
|
|
@@ -15,22 +65,34 @@ def ask_openrouter(input_text, history):
|
|
| 15 |
role = msg.get("role")
|
| 16 |
if role == "model":
|
| 17 |
role = "assistant"
|
|
|
|
| 18 |
if role in ("user", "assistant"):
|
| 19 |
-
messages.append({
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
messages.append({"role": "user", "content": input_text})
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
response = requests.post(
|
| 25 |
-
|
| 26 |
-
headers=
|
| 27 |
-
|
| 28 |
-
"Content-Type": "application/json",
|
| 29 |
-
},
|
| 30 |
-
json={
|
| 31 |
-
"model": "openai/gpt-oss-20b",
|
| 32 |
-
"messages": messages,
|
| 33 |
-
},
|
| 34 |
timeout=60,
|
| 35 |
)
|
| 36 |
response.raise_for_status()
|
|
@@ -48,13 +110,147 @@ def ask_openrouter(input_text, history):
|
|
| 48 |
{"role": "user", "content": input_text},
|
| 49 |
{"role": "assistant", "content": answer},
|
| 50 |
]
|
|
|
|
| 51 |
return answer, updated_history
|
| 52 |
|
| 53 |
except requests.exceptions.HTTPError as e:
|
| 54 |
raise gr.Error(
|
| 55 |
-
f"OpenRouter API error ({e.response.status_code}):
|
|
|
|
| 56 |
) from e
|
| 57 |
except requests.exceptions.RequestException as e:
|
| 58 |
raise gr.Error(f"OpenRouter request failed: {e}") from e
|
| 59 |
except ValueError as e:
|
| 60 |
-
raise gr.Error(f"OpenRouter returned invalid JSON: {e}") from e
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import requests
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
from google import genai
|
| 6 |
+
from google.genai import types
|
| 7 |
+
from gradio_client import Client
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
username = os.environ.get("APP_USERNAME")
|
| 12 |
+
password = os.environ.get("APP_PASSWORD")
|
| 13 |
+
hf_token = os.environ.get("HF_TOKEN")
|
| 14 |
+
|
| 15 |
+
# Client initialization (v1beta is required for Google Search as a tool)
|
| 16 |
+
client_genai = genai.Client(
|
| 17 |
+
api_key=os.environ.get("GEMINI_API_KEY"),
|
| 18 |
+
http_options=types.HttpOptions(api_version="v1beta"),
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
SYSTEM_PROMPT = (
|
| 22 |
+
"antworte kurz und knapp. "
|
| 23 |
+
"optimiere deine antwort für sprachausgabe."
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def build_message(input_text, history):
|
| 28 |
+
"""Der Gesprächsverlauf wird zu einem Transkript zusammengefasst."""
|
| 29 |
+
if not history:
|
| 30 |
+
return input_text
|
| 31 |
+
|
| 32 |
+
lines = []
|
| 33 |
+
for msg in history:
|
| 34 |
+
speaker = (
|
| 35 |
+
"Assistent"
|
| 36 |
+
if msg["role"] in ("model", "assistant")
|
| 37 |
+
else "Nutzer"
|
| 38 |
+
)
|
| 39 |
+
lines.append(f"{speaker}: {msg['content']}")
|
| 40 |
+
|
| 41 |
+
transcript = "\n".join(lines)
|
| 42 |
+
return (
|
| 43 |
+
f"Bisheriger Gesprächsverlauf:\n{transcript}\n\n"
|
| 44 |
+
f"Neue Nachricht des Nutzers:\n{input_text}"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
def ask_openrouter(input_text, history):
|
| 49 |
+
"""Sendet die Nachricht und den Verlauf an OpenRouter."""
|
| 50 |
key = os.getenv("OPENROUTER_API_KEY", "").strip()
|
| 51 |
if not key:
|
| 52 |
+
raise gr.Error(
|
| 53 |
+
"API key missing. Set the OPENROUTER_API_KEY environment variable."
|
| 54 |
+
)
|
| 55 |
|
| 56 |
input_text = (input_text or "").strip()
|
| 57 |
if not input_text:
|
|
|
|
| 65 |
role = msg.get("role")
|
| 66 |
if role == "model":
|
| 67 |
role = "assistant"
|
| 68 |
+
|
| 69 |
if role in ("user", "assistant"):
|
| 70 |
+
messages.append({
|
| 71 |
+
"role": role,
|
| 72 |
+
"content": msg["content"],
|
| 73 |
+
})
|
| 74 |
|
| 75 |
messages.append({"role": "user", "content": input_text})
|
| 76 |
|
| 77 |
+
url = "https://openrouter.ai/api/v1/chat/completions"
|
| 78 |
+
|
| 79 |
+
headers = {
|
| 80 |
+
"Authorization": f"Bearer {key}",
|
| 81 |
+
"Content-Type": "application/json",
|
| 82 |
+
# "HTTP-Referer": "https://your-app-url.com",
|
| 83 |
+
# "X-OpenRouter-Title": "Gradio OpenRouter App",
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
payload = {
|
| 87 |
+
"model": "openai/gpt-oss-20b",
|
| 88 |
+
"messages": messages,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
try:
|
| 92 |
response = requests.post(
|
| 93 |
+
url,
|
| 94 |
+
headers=headers,
|
| 95 |
+
json=payload,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
timeout=60,
|
| 97 |
)
|
| 98 |
response.raise_for_status()
|
|
|
|
| 110 |
{"role": "user", "content": input_text},
|
| 111 |
{"role": "assistant", "content": answer},
|
| 112 |
]
|
| 113 |
+
|
| 114 |
return answer, updated_history
|
| 115 |
|
| 116 |
except requests.exceptions.HTTPError as e:
|
| 117 |
raise gr.Error(
|
| 118 |
+
f"OpenRouter API error ({e.response.status_code}): "
|
| 119 |
+
f"{e.response.text}"
|
| 120 |
) from e
|
| 121 |
except requests.exceptions.RequestException as e:
|
| 122 |
raise gr.Error(f"OpenRouter request failed: {e}") from e
|
| 123 |
except ValueError as e:
|
| 124 |
+
raise gr.Error(f"OpenRouter returned invalid JSON: {e}") from e
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def tokenrouter(input_text):
|
| 128 |
+
client = OpenAI(
|
| 129 |
+
base_url="https://api.tokenrouter.com/v1",
|
| 130 |
+
api_key=os.environ.get("HF_TOKEN"),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
messages = [
|
| 134 |
+
{
|
| 135 |
+
"role": "system",
|
| 136 |
+
"content": "You are an intelligent assistant, please reply concisely.",
|
| 137 |
+
},
|
| 138 |
+
{"role": "user", "content": input_text},
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
stream = client.chat.completions.create(
|
| 142 |
+
model="qwen/qwen3.8-max",
|
| 143 |
+
messages=messages,
|
| 144 |
+
stream=True,
|
| 145 |
+
stream_options={"include_usage": True},
|
| 146 |
+
extra_body={},
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
content_parts = []
|
| 150 |
+
for chunk in stream:
|
| 151 |
+
if chunk.choices:
|
| 152 |
+
delta = chunk.choices[0].delta
|
| 153 |
+
if delta and delta.content:
|
| 154 |
+
content_parts.append(delta.content)
|
| 155 |
+
|
| 156 |
+
return "".join(content_parts)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def qwen(input_text):
|
| 160 |
+
client = Client("zai-org/GLM-4.5-Space")
|
| 161 |
+
result = client.predict(
|
| 162 |
+
msg=input_text,
|
| 163 |
+
sys_prompt="you are a helpful assistant",
|
| 164 |
+
thinking_enabled=False,
|
| 165 |
+
temperature=0.4,
|
| 166 |
+
api_name="/chat_wrapper",
|
| 167 |
+
)
|
| 168 |
+
return result
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def puter(input_text):
|
| 172 |
+
client = Client("mgokg/puter")
|
| 173 |
+
result = client.predict(
|
| 174 |
+
message=input_text,
|
| 175 |
+
model="gemini-2.5-flash-lite",
|
| 176 |
+
system_prompt="You are a helpful assistant.",
|
| 177 |
+
temperature=0.3,
|
| 178 |
+
max_tokens=8192,
|
| 179 |
+
web_search=True,
|
| 180 |
+
token_override="",
|
| 181 |
+
api_name="/chat",
|
| 182 |
+
)
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def generate_with_history(input_text, history):
|
| 187 |
+
"""
|
| 188 |
+
input_text: Die neue Nachricht
|
| 189 |
+
history: Eine Liste vorheriger Nachrichten
|
| 190 |
+
[{'role': '...', 'content': '...'}, ...]
|
| 191 |
+
"""
|
| 192 |
+
history = history or []
|
| 193 |
+
contents = []
|
| 194 |
+
|
| 195 |
+
# Verlauf in das von der GenAI API erwartete Format konvertieren.
|
| 196 |
+
for msg in history:
|
| 197 |
+
role = "model" if msg["role"] == "assistant" else msg["role"]
|
| 198 |
+
contents.append(
|
| 199 |
+
types.Content(
|
| 200 |
+
role=role,
|
| 201 |
+
parts=[types.Part.from_text(text=msg["content"])],
|
| 202 |
+
)
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
contents.append(
|
| 206 |
+
types.Content(
|
| 207 |
+
role="user",
|
| 208 |
+
parts=[types.Part.from_text(text=input_text)],
|
| 209 |
+
)
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
tools = [types.Tool(google_search=types.GoogleSearch())]
|
| 213 |
+
config = types.GenerateContentConfig(
|
| 214 |
+
tools=tools,
|
| 215 |
+
system_instruction=SYSTEM_PROMPT,
|
| 216 |
+
)
|
| 217 |
+
|
| 218 |
+
try:
|
| 219 |
+
response = client_genai.models.generate_content(
|
| 220 |
+
model="gemini-3.5-flash-lite",
|
| 221 |
+
contents=contents,
|
| 222 |
+
config=config,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
response_text = response.text
|
| 226 |
+
|
| 227 |
+
updated_history = history + [
|
| 228 |
+
{"role": "user", "content": input_text},
|
| 229 |
+
{"role": "assistant", "content": response_text},
|
| 230 |
+
]
|
| 231 |
+
|
| 232 |
+
return response_text, updated_history
|
| 233 |
+
|
| 234 |
+
except Exception as e:
|
| 235 |
+
return f"Error: {str(e)}", history
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# Gradio Blocks Interface
|
| 239 |
+
with gr.Blocks() as demo:
|
| 240 |
+
history_state = gr.State([])
|
| 241 |
+
|
| 242 |
+
input_box = gr.Textbox(label="Input", visible=True)
|
| 243 |
+
output_box = gr.Markdown(label="Response", visible=True)
|
| 244 |
+
|
| 245 |
+
btn = gr.Button("Submit", visible=True)
|
| 246 |
+
|
| 247 |
+
btn.click(
|
| 248 |
+
fn=ask_openrouter,
|
| 249 |
+
inputs=[input_box, history_state],
|
| 250 |
+
outputs=[output_box, history_state],
|
| 251 |
+
api_name="generate",
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
demo.launch()
|