mgokg commited on
Commit
ad2c811
·
verified ·
1 Parent(s): e9991ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -53
app.py CHANGED
@@ -1,65 +1,87 @@
1
- import os
2
- import asyncio
3
  import gradio as gr
 
 
4
  from google import genai
5
  from google.genai import types
6
- from mcp import ClientSession
7
- from mcp.client.sse import sse_client
8
 
9
- async def generate_response(input_text):
10
- mcp_url = "https://mgokg-db-timetable-api.hf.space/gradio_api/mcp/"
11
- try:
12
- client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
13
-
14
- # Verbindung zum MCP-Server via SSE (Server-Sent Events) [3]
15
- async with sse_client(url=mcp_url) as (read_stream, write_stream):
16
- async with ClientSession(read_stream, write_stream) as mcp_session:
17
- await mcp_session.initialize() [4]
18
-
19
- # Konfiguration der Tools (Google Search + MCP Tools) [4]
20
- generate_content_config = types.GenerateContentConfig(
21
- temperature=0.4,
22
- tools=[
23
- types.Tool(google_search=types.GoogleSearch()),
24
- mcp_session # Reicht MCP-Tools an Gemini durch [4]
25
- ],
26
- )
27
 
28
- response_text = ""
29
- # Stream-Generierung der Antwort [4]
30
- async for chunk in client.aio.models.generate_content_stream(
31
- model="gemini-flash-latest",
32
- contents=input_text,
33
- config=generate_content_config,
34
- ):
35
- if chunk.text:
36
- response_text += chunk.text
37
-
38
- return response_text, "" # Rückgabe für Markdown und Textbox-Reset [2]
 
 
 
 
 
 
 
 
 
 
39
 
 
 
 
 
 
40
  except Exception as e:
41
- return f"Verbindung zum DB-Fahrplan fehlgeschlagen: {str(e)}", ""
42
 
43
- # Wrapper für die synchrone Gradio-Umgebung [2]
44
- def gradio_wrapper(input_text):
45
- return asyncio.run(generate_response(input_text))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
 
47
- # Aufbau des ursprünglichen Interfaces [2]
48
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
49
- gr.Markdown("# 🚆 Gemini Flash + DB Timetable")
50
-
51
- with gr.Row():
52
- input_tx = gr.Textbox(
53
- label="Anfrage",
54
- placeholder="Wann fährt der nächste Zug von Berlin nach Hamburg?",
55
- lines=3
56
- )
57
-
58
- btn = gr.Button("Senden", variant="primary")
59
- output_md = gr.Markdown() # Bereich für die Antwort [2]
60
 
61
- # Event-Handling: Klick löst die Generierung aus
62
- btn.click(fn=gradio_wrapper, inputs=input_tx, outputs=[output_md, input_tx])
 
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
  if __name__ == '__main__':
65
- demo.launch()
 
 
 
 
 
 
 
 
 
1
+ import base64
 
2
  import gradio as gr
3
+ import os
4
+ import json
5
  from google import genai
6
  from google.genai import types
7
+ from gradio_client import Client
 
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
+ def clean_json_string(json_str):
11
+ """
12
+ Removes any comments or prefixes before the actual JSON content.
13
+ """
14
+ # Find the first occurrence of '{'
15
+ json_start = json_str.find('{')
16
+ if json_start == -1:
17
+ # If no '{' is found, try with '[' for arrays
18
+ json_start = json_str.find('[')
19
+ if json_start == -1:
20
+ return json_str # Return original if no JSON markers found
21
+
22
+ # Extract everything from the first JSON marker
23
+ cleaned_str = json_str[json_start:]
24
+ return cleaned_str
25
+ # Verify it's valid JSON
26
+ try:
27
+ json.loads(cleaned_str)
28
+ return cleaned_str
29
+ except json.JSONDecodeError:
30
+ return json_str # Return original if cleaning results in invalid JSON
31
 
32
+ def generate(input_text):
33
+ try:
34
+ client = genai.Client(
35
+ api_key=os.environ.get("GEMINI_API_KEY"),
36
+ )
37
  except Exception as e:
38
+ return f"Error initializing client: {e}. Make sure GEMINI_API_KEY is set."
39
 
40
+ model = "gemini-flash-latest"
41
+ contents = [
42
+ types.Content(
43
+ role="user",
44
+ parts=[
45
+ types.Part.from_text(text=f"{input_text}"),
46
+ ],
47
+ ),
48
+ ]
49
+ tools = [
50
+ types.Tool(google_search=types.GoogleSearch()),
51
+ ]
52
+ generate_content_config = types.GenerateContentConfig(
53
+ temperature=0.4,
54
+ thinking_config = types.ThinkingConfig(
55
+ thinking_budget=0,
56
+ ),
57
+ tools=tools,
58
+ response_mime_type="text/plain",
59
+ )
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ response_text = ""
63
+ try:
64
+ for chunk in client.models.generate_content_stream(
65
+ model=model,
66
+ contents=contents,
67
+ config=generate_content_config,
68
+ ):
69
+ response_text += chunk.text
70
+ except Exception as e:
71
+ return f"Error during generation: {e}"
72
+ data = response_text
73
+ #data = clean_json_string(response_text)
74
+ data = data[:-1]
75
+ return response_text, ""
76
+
77
 
78
  if __name__ == '__main__':
79
+
80
+ with gr.Blocks() as demo:
81
+ title=gr.Markdown("# Gemini 2.0 Flash + Websearch")
82
+ output_textbox = gr.Markdown()
83
+ input_textbox = gr.Textbox(lines=3, label="", placeholder="Enter message here...")
84
+ submit_button = gr.Button("send")
85
+ submit_button.click(fn=generate,inputs=input_textbox,outputs=[output_textbox, input_textbox])
86
+ demo.launch(show_error=True)
87
+