nicolaydef commited on
Commit
d5d3869
·
verified ·
1 Parent(s): 610b8d4

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +45 -35
main.py CHANGED
@@ -1,36 +1,46 @@
1
- import os
2
- import google.generativeai as genai
3
- from fastapi import FastAPI, HTTPException
4
- from pydantic import BaseModel
5
-
6
- app = FastAPI()
7
-
8
- # Получаем ключ из секретов HF
9
- genai.configure(api_key=os.environ.get("GEMINI_API_KEY"))
10
-
11
- model = genai.GenerativeModel("gemini-1.5-flash")
12
-
13
- class RequestData(BaseModel):
14
- context: str
15
- mood: str # 'fun', 'serious', 'neutral', 'angry'
16
-
17
- @app.post("/complete")
18
- async def complete_text(data: RequestData):
19
- try:
20
- # Настройка личности
21
- tone_instruction = ""
22
- if data.mood == "fun":
23
- tone_instruction = "Отвечай весело, используй сленг, эмодзи, будь на позитиве."
24
- elif data.mood == "serious":
25
- tone_instruction = "Отвечай максимально официально, сухо, деловой стиль, без воды."
26
- elif data.mood == "angry":
27
- tone_instruction = "Отвечай пассивно-агрессивно, кратко, с сарказмом. Ты устал от людей."
28
- else: # neutral
29
- tone_instruction = "Отвечай спокойно, нейтрально, как обычный помощник."
30
-
31
- prompt = f"System: {tone_instruction}. Продолжи фразу пользователя. Не повторяй ввод. Только продолжение.\n\nUser Input: {data.context}\nOutput:"
32
-
33
- response = model.generate_content(prompt)
34
- return {"completion": response.text.strip()}
35
- except Exception as e:
 
 
 
 
 
 
 
 
 
 
36
  raise HTTPException(status_code=500, detail=str(e))
 
1
+ import os
2
+ import google.generativeai as genai
3
+ from fastapi import FastAPI, HTTPException, Request
4
+ from pydantic import BaseModel
5
+ import traceback # Добавили для отладки
6
+
7
+ app = FastAPI()
8
+
9
+ # Читаем ключ
10
+ api_key = os.environ.get("GEMINI_API_KEY")
11
+
12
+ if not api_key:
13
+ print("!!! ОШИБКА: GEMINI_API_KEY не найден в переменных окружения !!!")
14
+ else:
15
+ print(f"Ключ найден, первые символы: {api_key[:5]}...")
16
+ genai.configure(api_key=api_key)
17
+
18
+ # Попробуем gemini-pro, она доступна всем
19
+ model = genai.GenerativeModel("gemini-1.5-flash")
20
+
21
+ class RequestData(BaseModel):
22
+ context: str
23
+ mood: str
24
+
25
+ @app.post("/complete")
26
+ async def complete_text(data: RequestData):
27
+ try:
28
+ print(f"Получен запрос: {data.context[:20]}...") # Лог запроса
29
+
30
+ tone_instruction = "Отвечай нейтрально."
31
+ if data.mood == "fun": tone_instruction = "Отвечай весело."
32
+ elif data.mood == "serious": tone_instruction = "Отвечай серьезно."
33
+ elif data.mood == "angry": tone_instruction = "Отвечай злобно."
34
+
35
+ prompt = f"System: {tone_instruction}. Продолжи: {data.context}"
36
+
37
+ response = model.generate_content(prompt)
38
+ print(f"Ответ от Gemini получен: {response.text[:20]}...")
39
+
40
+ return {"completion": response.text.strip()}
41
+ except Exception as e:
42
+ # ВОТ ЭТО ПОКАЖЕТ ОШИБКУ В ЛОГАХ
43
+ error_msg = traceback.format_exc()
44
+ print("!!! КРИТИЧЕСКАЯ ОШИБКА !!!")
45
+ print(error_msg)
46
  raise HTTPException(status_code=500, detail=str(e))