Spaces:
Running
Running
import gradio as gr | |
import google.generativeai as genai | |
import os | |
# λλ²κΉ : νκ²½λ³μ νμΈ | |
print("=== νκ²½λ³μ λλ²κΉ ===") | |
print(f"GEMINI_API_KEY μ‘΄μ¬ μ¬λΆ: {'GEMINI_API_KEY' in os.environ}") | |
api_key = os.environ.get("GEMINI_API_KEY") | |
if api_key: | |
print(f"API ν€ κΈΈμ΄: {len(api_key)}") | |
print(f"API ν€ μμ: {api_key[:10]}...") | |
else: | |
print("API ν€κ° μμ΅λλ€!") | |
print("μ¬μ© κ°λ₯ν νκ²½λ³μλ€:") | |
for key in os.environ.keys(): | |
if "KEY" in key or "SECRET" in key: | |
print(f" - {key}") | |
# μμ€ν ν둬ννΈ | |
SYSTEM_PROMPT = "λ°ν λλ³Έμ λ§λ€μ΄μ£Όλ μ±λ΄μ λλ€. λ°νν λ΄μ©μ μ λ ₯νλ©΄ 'μλνλ©΄ ~μ΄κΈ° λλ¬Έμ λλ€'λ‘ λλ³Έμ λ§λ€μ΄μ€λλ€" | |
def chat(message, history): | |
# API ν€ λ€μ νμΈ | |
api_key = os.environ.get("GEMINI_API_KEY") | |
if not api_key: | |
return f"""β API ν€κ° μ€μ λμ§ μμμ΅λλ€. | |
**ν΄κ²° λ°©λ²:** | |
1. Hugging Face Spaceμ βοΈ Settings νμΌλ‘ μ΄λ | |
2. 'Repository secrets' μΉμ μ°ΎκΈ° | |
3. 'New secret' λ²νΌ ν΄λ¦ | |
4. Name: `GEMINI_API_KEY` (μ νν μ΄λ κ² μ λ ₯) | |
5. Value: λΉμ μ Gemini API ν€ λΆμ¬λ£κΈ° | |
6. 'Save' ν΄λ¦ | |
7. Spaceλ₯Ό μ¬μμ (Settings β Factory reboot) | |
νμ¬ μν: API ν€κ° {'μμ' if api_key else 'μμ'} | |
""" | |
try: | |
# API μ€μ | |
genai.configure(api_key=api_key) | |
model = genai.GenerativeModel( | |
'gemini-1.5-flash', | |
system_instruction=SYSTEM_PROMPT | |
) | |
# λν κΈ°λ‘ λ³ν | |
chat_history = [] | |
for human, assistant in history: | |
if human: | |
chat_history.append({"role": "user", "parts": [human]}) | |
if assistant: | |
chat_history.append({"role": "model", "parts": [assistant]}) | |
# μ±ν μΈμ μμ | |
chat_session = model.start_chat(history=chat_history) | |
# μλ΅ μμ± | |
response = chat_session.send_message(message) | |
return response.text | |
except Exception as e: | |
error_msg = str(e) | |
if "API_KEY_INVALID" in error_msg: | |
return "β API ν€κ° μ ν¨νμ§ μμ΅λλ€. μ¬λ°λ₯Έ Gemini API ν€μΈμ§ νμΈνμΈμ." | |
else: | |
return f"β μ€λ₯ λ°μ: {error_msg}" | |
# Gradio μΈν°νμ΄μ€ | |
demo = gr.ChatInterface( | |
fn=chat, | |
title="π€ λ Όλ¦¬μ μΌλ‘ λ§νλ λ°νλμ°λ―Έ Gemini μ±λ΄", | |
description=f"""λ Όλ¦¬μ μΌλ‘ λ°ννλ λ°©λ²μ λμμ€λλ€. | |
**μν**: API ν€κ° {'β μ€μ λ¨' if api_key else 'β μ€μ λμ§ μμ'} | |
[API ν€ λ°κΈ°](https://aistudio.google.com/app/apikey) | |
""" | |
) | |
if __name__ == "__main__": | |
demo.launch() |