| import streamlit as st |
| from google import genai |
| import os |
|
|
| |
| api_key = os.getenv("GOOGLE_API_KEY") |
| |
| if not api_key: |
| raise EnvironmentError("GOOGLE_API_KEY not set in environment variables.") |
|
|
| |
| os.environ["GOOGLE_API_KEY"] = api_key |
| |
| client = genai.Client() |
| MODEL_ID = "gemini-2.0-flash" |
|
|
| |
| def chat_with_gemini(message, history): |
| try: |
| response = client.models.generate_content( |
| model=MODEL_ID, |
| contents=message, |
| config={"tools": [{"google_search": {}}]}, |
| ) |
| return response.text |
| except Exception as e: |
| return f"Error: {str(e)}" |
|
|
| |
| st.title("Gemini Chatbot (with Google Search)") |
| st.write("Ask anything and get responses powered by Gemini 2.0 Flash.") |
|
|
| |
| if 'history' not in st.session_state: |
| st.session_state['history'] = [] |
|
|
| |
| user_input = st.text_input("You:", "") |
|
|
| |
| if st.button("Send"): |
| if user_input: |
| |
| st.session_state.history.append({"role": "user", "message": user_input}) |
| |
| |
| gemini_response = chat_with_gemini(user_input, st.session_state.history) |
| |
| |
| st.session_state.history.append({"role": "assistant", "message": gemini_response}) |
| |
| |
| for chat in st.session_state.history: |
| if chat["role"] == "user": |
| st.chat_message("user").markdown(chat["message"]) |
| else: |
| st.chat_message("assistant").markdown(chat["message"]) |