mgokg commited on
Commit
d8f67c2
·
verified ·
1 Parent(s): 868e79a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -23
app.py CHANGED
@@ -4,57 +4,113 @@ import os
4
  import json
5
  from google import genai
6
  from google.genai import types
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
  def generate1(input_text):
9
  client = genai.Client(
10
  api_key=os.environ.get("GEMINI_API_KEY"),
11
  )
12
 
13
- model = "gemini-flash-latest"
14
  contents = [
15
  types.Content(
16
  role="user",
17
  parts=[
18
- types.Part.from_text(text=f"return json object with keys name and email. name = {input_text} search the web for the email value. return json object only, no additional text or comments"),
19
  ],
20
  ),
21
  ]
22
-
23
- # Updated tool config for Gemini 2.0
24
  tools = [
25
- types.Tool(google_search_retrieval=types.DynamicRetrievalConfig(mode="DYNAMIC"))
26
  ]
27
-
28
  generate_content_config = types.GenerateContentConfig(
29
  temperature=0.45,
30
  tools=tools,
31
  response_mime_type="text/plain",
32
  )
33
 
34
- full_response = ""
35
- # We yield two values: the accumulated response and an empty string (to clear the input)
36
  for chunk in client.models.generate_content_stream(
37
  model=model,
38
  contents=contents,
39
  config=generate_content_config,
40
  ):
41
- if chunk.text:
42
- full_response += chunk.text
43
- # Yielding [Output, Input]
44
- yield full_response, gr.update(value="")
45
 
46
  if __name__ == '__main__':
 
47
  with gr.Blocks() as demo:
48
- gr.Markdown("# Gemini 2.0 Flash + Websearch")
49
  output_textbox = gr.Markdown()
50
- input_textbox = gr.Textbox(lines=3, label="Input", placeholder="Enter name here...")
51
- submit_button = gr.Button("Send")
52
-
53
- # Pointing to generate1 which now yields two values
54
- submit_button.click(
55
- fn=generate1,
56
- inputs=input_textbox,
57
- outputs=[output_textbox, input_textbox]
58
- )
59
-
60
  demo.launch(show_error=True)
 
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
 
77
  def generate1(input_text):
78
  client = genai.Client(
79
  api_key=os.environ.get("GEMINI_API_KEY"),
80
  )
81
 
82
+ model = "gemini-3-flash-preview"
83
  contents = [
84
  types.Content(
85
  role="user",
86
  parts=[
87
+ types.Part.from_text(text=f"return json object with keys name and email. name = {input_text} search the web for the email value. return json object only, no additional text or comments"),
88
  ],
89
  ),
90
  ]
 
 
91
  tools = [
92
+ types.Tool(googleSearchRetrieval=types.DynamicRetrievalConfig(dynamicThreshold=0.3, mode=types.DynamicRetrievalConfigMode.MODE_DYNAMIC)),
93
  ]
 
94
  generate_content_config = types.GenerateContentConfig(
95
  temperature=0.45,
96
  tools=tools,
97
  response_mime_type="text/plain",
98
  )
99
 
 
 
100
  for chunk in client.models.generate_content_stream(
101
  model=model,
102
  contents=contents,
103
  config=generate_content_config,
104
  ):
105
+ print(chunk.text, end="")
106
+
 
 
107
 
108
  if __name__ == '__main__':
109
+
110
  with gr.Blocks() as demo:
111
+ title=gr.Markdown("# Gemini 2.0 Flash + Websearch")
112
  output_textbox = gr.Markdown()
113
+ input_textbox = gr.Textbox(lines=3, label="", placeholder="Enter event details here...")
114
+ submit_button = gr.Button("send")
115
+ submit_button.click(fn=generate,inputs=input_textbox,outputs=[output_textbox, input_textbox])
 
 
 
 
 
 
 
116
  demo.launch(show_error=True)