| import os |
| import gradio as gr |
| from google import genai |
| from google.genai import types |
|
|
| |
| 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 = [] |
|
|
| |
| |
| contents = [] |
| for msg in history: |
| contents.append(types.Content( |
| role=msg["role"], |
| parts=[types.Part.from_text(text=msg["content"])] |
| )) |
| |
| |
| 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-flash-lite-latest", |
| contents=contents, |
| config=config, |
| ) |
| |
| response_text = response.text |
| |
| |
| history.append({"role": "user", "content": input_text}) |
| history.append({"role": "model", "content": response_text}) |
| |
| |
| return response_text, history |
|
|
| except Exception as e: |
| return f"Error: {str(e)}", history |
|
|
| |
| with gr.Blocks() as demo: |
| |
| history_state = gr.State([]) |
| |
| |
| 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() |