mgokg commited on
Commit
016620f
·
verified ·
1 Parent(s): df08b6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -15
app.py CHANGED
@@ -1,21 +1,84 @@
1
- async def generate(input_text):
2
- if not GEMINI_API_KEY:
3
- yield "Error: GEMINI_API_KEY is not set.", ""
4
- return # Stops the generator
 
 
 
5
 
6
- # ... (setup code) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
 
8
  try:
9
- yield "Thinking...", "" # UI update
10
-
11
- # ... (logic loop) ...
12
-
13
- if tool_calls:
14
- yield "Fetching live train data from MCP server...", ""
15
- # ... (execute tool) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- # Final result
18
- yield response.text, ""
19
 
 
 
 
 
 
 
 
 
20
  except Exception as e:
21
- yield f"### Logic Error\n{str(e)}", ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ def clean_json_string(json_str):
10
+ """
11
+ Removes any comments or prefixes before the actual JSON content.
12
+ """
13
+ # Find the first occurrence of '{'
14
+ json_start = json_str.find('{')
15
+ if json_start == -1:
16
+ # If no '{' is found, try with '[' for arrays
17
+ json_start = json_str.find('[')
18
+ if json_start == -1:
19
+ return json_str # Return original if no JSON markers found
20
+
21
+ # Extract everything from the first JSON marker
22
+ cleaned_str = json_str[json_start:]
23
+ return cleaned_str
24
+ # Verify it's valid JSON
25
+ try:
26
+ json.loads(cleaned_str)
27
+ return cleaned_str
28
+ except json.JSONDecodeError:
29
+ return json_str # Return original if cleaning results in invalid JSON
30
 
31
+ def generate(input_text):
32
  try:
33
+ client = genai.Client(
34
+ api_key=os.environ.get("GEMINI_API_KEY"),
35
+ )
36
+ except Exception as e:
37
+ return f"Error initializing client: {e}. Make sure GEMINI_API_KEY is set."
38
+
39
+ model = "gemini-flash-latest"
40
+ contents = [
41
+ types.Content(
42
+ role="user",
43
+ parts=[
44
+ types.Part.from_text(text=input_text),
45
+ ],
46
+ ),
47
+ ]
48
+ tools = [
49
+ types.Tool(google_search=types.GoogleSearch()),
50
+ ]
51
+ generate_content_config = types.GenerateContentConfig(
52
+ temperature=0.4,
53
+ thinking_config = types.ThinkingConfig(
54
+ thinking_budget=0,
55
+ ),
56
+ tools=tools,
57
+ response_mime_type="text/plain",
58
+ )
59
 
 
 
60
 
61
+ response_text = ""
62
+ try:
63
+ for chunk in client.models.generate_content_stream(
64
+ model=model,
65
+ contents=contents,
66
+ config=generate_content_config,
67
+ ):
68
+ response_text += chunk.text
69
  except Exception as e:
70
+ return f"Error during generation: {e}"
71
+ data = clean_json_string(response_text)
72
+ data = data[:-1]
73
+ return response_text, ""
74
+
75
+
76
+ if __name__ == '__main__':
77
+
78
+ with gr.Blocks() as demo:
79
+ title=gr.Markdown("# Gemini 2.0 Flash + Websearch")
80
+ output_textbox = gr.Markdown()
81
+ input_textbox = gr.Textbox(lines=3, label="", placeholder="Enter message here...")
82
+ submit_button = gr.Button("send")
83
+ submit_button.click(fn=generate,inputs=input_textbox,outputs=[output_textbox, input_textbox])
84
+ demo.launch(show_error=True)