Spaces:
Running
Running
File size: 2,765 Bytes
226a535 cb245e5 d034f8c 3271c7b 732091b 3271c7b d034f8c 732091b 3271c7b 732091b 3271c7b cb245e5 732091b 3271c7b 30b8dce 1b77547 30b8dce 732091b 3271c7b 732091b 1b77547 3271c7b 732091b 3271c7b 732091b 3271c7b 1b77547 3271c7b cb245e5 226a535 732091b |
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 72 73 74 75 76 77 78 79 80 81 82 83 84 |
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() |