File size: 2,150 Bytes
f2c98e1
54faf8d
9849652
59e0c66
 
 
9849652
59e0c66
 
 
54faf8d
f02c4ad
54faf8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f02c4ad
54faf8d
 
 
 
 
 
f02c4ad
59e0c66
f2c98e1
59e0c66
f2c98e1
59e0c66
 
 
 
54faf8d
59e0c66
 
 
 
 
54faf8d
59e0c66
 
 
 
 
54faf8d
 
 
 
59e0c66
54faf8d
 
f02c4ad
54faf8d
 
f02c4ad
54faf8d
 
f2c98e1
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
# 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()