|
|
|
import time |
|
import gradio as gr |
|
import google.generativeai as genai |
|
import os |
|
|
|
|
|
api_key = os.getenv('GOOGLE_API_KEY') |
|
if not api_key: |
|
raise ValueError("請設置 'GOOGLE_API_KEY' 環境變數") |
|
|
|
|
|
genai.configure(api_key=api_key) |
|
|
|
|
|
try: |
|
model = genai.GenerativeModel('gemini-1.5-pro') |
|
chat = model.start_chat(history=[]) |
|
print("模型載入成功。") |
|
except Exception as e: |
|
raise ValueError(f"無法載入模型:{e}") |
|
|
|
|
|
def transform_history(history): |
|
new_history = [] |
|
for chat in history: |
|
new_history.append({"parts": [{"text": chat[0]}], "role": "user"}) |
|
new_history.append({"parts": [{"text": chat[1]}], "role": "model"}) |
|
return new_history |
|
|
|
|
|
def response(message, history): |
|
global chat |
|
|
|
chat.history = transform_history(history) |
|
|
|
|
|
response = chat.send_message(message) |
|
response.resolve() |
|
|
|
|
|
for i in range(len(response.text)): |
|
time.sleep(0.05) |
|
yield response.text[: i+1] |
|
|
|
|
|
gr.ChatInterface(response, |
|
title='Gemini Chat', |
|
textbox=gr.Textbox(placeholder="Question to Gemini")).launch(share=True) |
|
|