Update app.py
Browse files
app.py
CHANGED
|
@@ -1,207 +1,60 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
from google import genai
|
| 4 |
-
from google.genai import types
|
| 5 |
-
from gradio_client import Client
|
| 6 |
-
import requests
|
| 7 |
-
|
| 8 |
-
username = os.environ.get("APP_USERNAME")
|
| 9 |
-
password = os.environ.get("APP_PASSWORD")
|
| 10 |
-
hf_token = os.environ.get("HF_TOKEN")
|
| 11 |
-
|
| 12 |
-
# Client initialization (v1beta is required for Google Search as a tool)
|
| 13 |
-
client_genai = genai.Client(
|
| 14 |
-
api_key=os.environ.get("GEMINI_API_KEY"),
|
| 15 |
-
http_options=types.HttpOptions(api_version="v1beta"),
|
| 16 |
-
)
|
| 17 |
-
|
| 18 |
-
SYSTEM_PROMPT = "antworte kurz und knapp. optimiere deine antwort für sprachausgabe."
|
| 19 |
-
|
| 20 |
-
def build_message(input_text, history):
|
| 21 |
-
"""Der Gesprächsverlauf wird zu einem Transkript zusammengefasst."""
|
| 22 |
-
if not history:
|
| 23 |
-
return input_text
|
| 24 |
-
|
| 25 |
-
lines = []
|
| 26 |
-
for msg in history:
|
| 27 |
-
speaker = "Assistent" if msg["role"] in ("model", "assistant") else "Nutzer"
|
| 28 |
-
lines.append(f"{speaker}: {msg['content']}")
|
| 29 |
-
|
| 30 |
-
transcript = "\n".join(lines)
|
| 31 |
-
return (
|
| 32 |
-
f"Bisheriger Gesprächsverlauf:\n{transcript}\n\n"
|
| 33 |
-
f"Neue Nachricht des Nutzers:\n{input_text}"
|
| 34 |
-
)
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
def ask_openrouter(
|
| 38 |
-
input_text: str,
|
| 39 |
-
model: str = "openai/gpt-oss-20b",
|
| 40 |
-
system_prompt: str = "",
|
| 41 |
-
api_key: str = "",
|
| 42 |
-
) -> str:
|
| 43 |
-
"""Sends a prompt directly to the OpenRouter Chat Completions endpoint."""
|
| 44 |
-
key = api_key.strip() or os.getenv("OPENROUTER_API_KEY")
|
| 45 |
if not key:
|
| 46 |
-
raise gr.Error(
|
| 47 |
-
"API key missing. Enter it in the UI or set OPENROUTER_API_KEY."
|
| 48 |
-
)
|
| 49 |
|
| 50 |
-
|
|
|
|
| 51 |
raise gr.Error("Please enter a prompt.")
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
headers = {
|
| 56 |
-
"Authorization": f"Bearer {key}",
|
| 57 |
-
"Content-Type": "application/json",
|
| 58 |
-
#"HTTP-Referer": "https://your-app-url.com",
|
| 59 |
-
#"X-OpenRouter-Title": "Gradio OpenRouter App",
|
| 60 |
-
}
|
| 61 |
-
|
| 62 |
-
messages = []
|
| 63 |
-
if system_prompt.strip():
|
| 64 |
-
messages.append({"role": "system", "content": system_prompt.strip()})
|
| 65 |
-
messages.append({"role": "user", "content": prompt})
|
| 66 |
-
|
| 67 |
-
payload = {
|
| 68 |
-
"model": model.strip() or "openai/gpt-4o-mini",
|
| 69 |
-
"messages": messages,
|
| 70 |
-
}
|
| 71 |
-
|
| 72 |
-
try:
|
| 73 |
-
response = requests.post(url, headers=headers, json=payload, timeout=60)
|
| 74 |
-
response.raise_for_status()
|
| 75 |
-
data = response.json()
|
| 76 |
-
return data["choices"][0]["message"]["content"]
|
| 77 |
-
except requests.exceptions.HTTPError as e:
|
| 78 |
-
raise gr.Error(f"OpenRouter API error ({response.status_code}): {response.text}")
|
| 79 |
-
except Exception as e:
|
| 80 |
-
raise gr.Error(f"Request failed: {str(e)}")
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
from openai import OpenAI
|
| 84 |
-
def tokenrouter(input_text):
|
| 85 |
-
client = OpenAI(
|
| 86 |
-
base_url='https://api.tokenrouter.com/v1',
|
| 87 |
-
api_key=os.environ.get("HF_TOKEN"),
|
| 88 |
-
)
|
| 89 |
|
| 90 |
-
messages = [
|
| 91 |
-
{"role": "system", "content": "You are an intelligent assistant, please reply concisely."},
|
| 92 |
-
{"role": "user", "content": "Hello, what kind of model are you?"},
|
| 93 |
-
]
|
| 94 |
|
| 95 |
-
stream = client.chat.completions.create(
|
| 96 |
-
model="qwen/qwen3.8-max",
|
| 97 |
-
messages=messages,
|
| 98 |
-
stream=True,
|
| 99 |
-
stream_options={"include_usage": True},
|
| 100 |
-
extra_body={}
|
| 101 |
-
)
|
| 102 |
-
|
| 103 |
-
content_parts = []
|
| 104 |
-
for chunk in stream:
|
| 105 |
-
if chunk.choices:
|
| 106 |
-
delta = chunk.choices[0].delta
|
| 107 |
-
if delta and delta.content:
|
| 108 |
-
content_parts.append(delta.content)
|
| 109 |
-
|
| 110 |
-
full_content = "".join(content_parts)
|
| 111 |
-
|
| 112 |
-
return full_content
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
def qwen(input_text):
|
| 116 |
-
client = Client("zai-org/GLM-4.5-Space")
|
| 117 |
-
result = client.predict(
|
| 118 |
-
msg=input_text,
|
| 119 |
-
sys_prompt="you are a helpful assistent",
|
| 120 |
-
thinking_enabled=False,
|
| 121 |
-
temperature=0.4,
|
| 122 |
-
api_name="/chat_wrapper"
|
| 123 |
-
)
|
| 124 |
-
return result
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
def puter(input_text):
|
| 128 |
-
client = Client("mgokg/puter")
|
| 129 |
-
result = client.predict(
|
| 130 |
-
message=input_text,
|
| 131 |
-
model="gemini-2.5-flash-lite",
|
| 132 |
-
system_prompt="You are a helpful assistant.",
|
| 133 |
-
temperature=0.3,
|
| 134 |
-
max_tokens=8192,
|
| 135 |
-
web_search=True,
|
| 136 |
-
token_override="",
|
| 137 |
-
api_name="/chat",
|
| 138 |
-
)
|
| 139 |
-
return result
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
def generate_with_history(input_text, history):
|
| 144 |
-
"""
|
| 145 |
-
- input_text: Die neue Nachricht
|
| 146 |
-
- history: Eine Liste von vorherigen Nachrichten [{'role': '...', 'content': '...'}, ...]
|
| 147 |
-
"""
|
| 148 |
-
if history is None:
|
| 149 |
-
history = []
|
| 150 |
-
|
| 151 |
-
contents = []
|
| 152 |
-
|
| 153 |
-
# Verlauf in das von der GenAI API erwartete Format konvertieren
|
| 154 |
for msg in history:
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
)
|
|
|
|
| 159 |
|
| 160 |
-
|
| 161 |
-
contents.append(types.Content(
|
| 162 |
-
role="user",
|
| 163 |
-
parts=[types.Part.from_text(text=input_text)]
|
| 164 |
-
))
|
| 165 |
-
|
| 166 |
-
tools = [types.Tool(google_search=types.GoogleSearch())]
|
| 167 |
-
config = types.GenerateContentConfig(
|
| 168 |
-
tools=tools,
|
| 169 |
-
system_instruction=SYSTEM_PROMPT,
|
| 170 |
-
)
|
| 171 |
|
| 172 |
try:
|
| 173 |
-
response =
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
)
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
history.append({"role": "user", "content": input_text})
|
| 183 |
-
history.append({"role": "model", "content": response_text})
|
| 184 |
-
|
| 185 |
-
return response_text, history
|
| 186 |
-
|
| 187 |
-
except Exception as e:
|
| 188 |
-
return f"Error: {str(e)}", history
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
# Gradio Blocks Interface
|
| 192 |
-
with gr.Blocks() as demo:
|
| 193 |
-
history_state = gr.State([])
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
|
|
|
| 197 |
|
| 198 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
|
|
|
| 1 |
+
def ask_openrouter(input_text, history):
|
| 2 |
+
key = os.getenv("OPENROUTER_API_KEY", "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
if not key:
|
| 4 |
+
raise gr.Error("Set the OPENROUTER_API_KEY environment variable.")
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
input_text = (input_text or "").strip()
|
| 7 |
+
if not input_text:
|
| 8 |
raise gr.Error("Please enter a prompt.")
|
| 9 |
|
| 10 |
+
history = history or []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
|
|
|
|
|
|
|
|
|
| 13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
for msg in history:
|
| 15 |
+
role = msg.get("role")
|
| 16 |
+
if role == "model":
|
| 17 |
+
role = "assistant"
|
| 18 |
+
if role in ("user", "assistant"):
|
| 19 |
+
messages.append({"role": role, "content": msg["content"]})
|
| 20 |
|
| 21 |
+
messages.append({"role": "user", "content": input_text})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
try:
|
| 24 |
+
response = requests.post(
|
| 25 |
+
"https://openrouter.ai/api/v1/chat/completions",
|
| 26 |
+
headers={
|
| 27 |
+
"Authorization": f"Bearer {key}",
|
| 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()
|
| 37 |
+
data = response.json()
|
| 38 |
|
| 39 |
+
choices = data.get("choices") or []
|
| 40 |
+
if not choices:
|
| 41 |
+
raise gr.Error(f"OpenRouter returned no choices: {data}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
answer = choices[0].get("message", {}).get("content")
|
| 44 |
+
if not answer:
|
| 45 |
+
raise gr.Error(f"OpenRouter returned an empty response: {data}")
|
| 46 |
|
| 47 |
+
updated_history = 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}): {e.response.text}"
|
| 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
|