File size: 2,147 Bytes
0804f89
298a5b1
0abe445
 
cb83081
11b0a8c
6a4db8d
0abe445
11b0a8c
6a4db8d
11b0a8c
 
6a4db8d
11b0a8c
 
 
 
 
 
 
 
 
 
 
70844b7
11b0a8c
 
 
 
 
 
70844b7
 
1f1770e
6a4db8d
 
0ee752d
6a4db8d
 
 
11b0a8c
 
 
 
 
 
 
 
 
 
6a4db8d
11b0a8c
70844b7
11b0a8c
6a4db8d
437d052
11b0a8c
6a4db8d
437d052
 
 
 
 
6a4db8d
11b0a8c
 
 
 
6a4db8d
 
70844b7
b0585c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
import gradio as gr
from google import genai
from google.genai import types

# Client initialization
client_genai = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))

def generate_with_history(input_text, history):
    """
    - input_text: The new message from JS
    - history: A list of previous messages [user, model, user, model...]
    """
    if history is None:
        history = []

    # Build the contents list including history
    # Gemini API expects a list of Content objects
    contents = []
    for msg in history:
        contents.append(types.Content(
            role=msg["role"],
            parts=[types.Part.from_text(text=msg["content"])]
        ))
    
    # Add the current user prompt
    contents.append(types.Content(
        role="user",
        parts=[types.Part.from_text(text=input_text)]
    ))

    tools = [types.Tool(google_search=types.GoogleSearch())]
    config = types.GenerateContentConfig(tools=tools)

    try:
        response = client_genai.models.generate_content(
            model="gemini-2.5-flash-lite",
            contents=contents,
            config=config,
        )
        
        response_text = response.text
        
        # Update history: add the current exchange
        history.append({"role": "user", "content": input_text})
        history.append({"role": "model", "content": response_text})
        
        # Return the response for JS and the updated history for the State
        return response_text, history

    except Exception as e:
        return f"Error: {str(e)}", history

# Building the Blocks interface
with gr.Blocks() as demo:
    # State component (always invisible)
    history_state = gr.State([])
    
    # Change visible=False to True (or remove it)
    input_box = gr.Textbox(label="Input", visible=True) 
    output_box = gr.Markdown(label="Response", visible=True)
    
    btn = gr.Button("Submit", visible=True)
    
    btn.click(
        fn=generate_with_history,
        inputs=[input_box, history_state],
        outputs=[output_box, history_state],
        api_name="generate"
    )
if __name__ == "__main__":
    demo.launch()