# Streamlit Gemini Chat Logger (不使用 CSV) import streamlit as st import google.generativeai as genai import os from datetime import datetime # 設定 Streamlit 頁面 st.set_page_config(page_title="Gemini Chat Logger", page_icon="🤖") # API 金鑰管理 def get_api_key(): api_key = os.environ.get("GOOGLE_API_KEY") if not api_key: try: api_key = st.secrets["GOOGLE_API_KEY"] except KeyError: st.warning(""" ### 🔑 API 金鑰未找到 請設定 Google API 金鑰: 1. 環境變數:設定 `GOOGLE_API_KEY` 2. Streamlit secrets:在 `.streamlit/secrets.toml` 中添加 `GOOGLE_API_KEY` 3. 在下方輸入 API 金鑰 """) api_key = st.text_input("輸入您的 Google API 金鑰", type="password") return api_key # 配置 API 金鑰 api_key = get_api_key() if api_key: try: genai.configure(api_key=api_key) except Exception as e: st.error(f"配置 API 金鑰時發生錯誤: {e}") else: st.stop() # 主應用程式 def main(): st.title("🤖 Gemini Chat Logger (不含 CSV)") if "messages" not in st.session_state: st.session_state.messages = [] # 顯示歷史訊息 for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # 使用者輸入 if prompt := st.chat_input("輸入您的訊息"): st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) try: model = genai.GenerativeModel("gemini-1.5-flash") response = model.generate_content(prompt) model_response = response.text.strip() st.session_state.messages.append({"role": "assistant", "content": model_response}) with st.chat_message("assistant"): st.markdown(model_response) except Exception as e: st.error(f"生成回應時發生錯誤: {e}") # 執行主應用程式 if __name__ == "__main__": main()