-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
101 lines (82 loc) · 3.66 KB
/
api.py
File metadata and controls
101 lines (82 loc) · 3.66 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
from fastapi import FastAPI ,Body
from fastapi.middleware.cors import CORSMiddleware # הוספה של זה
import os
from dotenv import load_dotenv
# ייבוא הפונקציות מה-DB
import db
from recipe import Recipe
import google.generativeai as genai
load_dotenv()
API_KEY = os.getenv("GEMINI_API_KEY")
if not API_KEY:
# הדפסה שתעזור לך לדבג אם המפתח לא נטען
print("CRITICAL ERROR: API_KEY not found in environment variables!")
else:
genai.configure(api_key=API_KEY)
# ניסיון להשתמש בשם המודל הבסיסי ביותר (הכי בטוח למניעת 404)
model = genai.GenerativeModel('models/gemini-2.5-flash')
# בדיקה בטרמינל אילו מודלים זמינים עבורך
try:
print("--- Checking available models ---")
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
print(f"Available: {m.name}")
print("---------------------------------")
except Exception as e:
print(f"Could not list models: {e}")
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # מאפשר לכל דף אינטרנט לגשת לשרת שלך
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# נקודת קצה חדשה לצ'אט על מתכון ספציפי
@app.post("/recipes/{recipe_id}/ask")
def ask_about_recipe(recipe_id: int, question: str = Body(embed=True)):
# 1. שליפת המתכון מה-DB שלך כדי שה-AI ידע על מה מדובר
recipe = db.get_recipe_by_id(recipe_id)
if "error" in recipe:
return recipe
# 2. בניית הפרומפט (ההנחיה) ל-AI
prompt = f"""
אתה עוזר מטבח חכם. קיבלת שאלה על המתכון הבא:
שם המתכון: {recipe['RecipeName']}
מצרכים: {recipe['Products']}
אופן ההכנה: {recipe['PreparationMethod']}
השאלה של המשתמש היא: {question}
אנא ענה בצורה ברורה ובעברית, אדיבה ומקצועית ואם השאלה לא קשורה למתכונים, החזר הודעה קבועה ומנומסת שמסבירה שהבוט עוסק רק במתכונים..
"""
try:
# 3. שליחה ל-Gemini
response = model.generate_content(prompt)
return {"answer": response.text}
except Exception as e:
print(f"Gemini Error: {str(e)}") # הדפסה ללוג של השרת
return {"error": "אירעה שגיאה בחיבור לבינה המלאכותית. נסה שוב מאוחר יותר."}
@app.get("/recipes")
def read_all_recipes_api(): # שם שונה מהפונקציה ב-DB
return db.get_all_recipes()
@app.get("/recipes/id/{recipe_id}")
def read_recipe_by_id_api(recipe_id: int):
return db.get_recipe_by_id(recipe_id)
@app.get("/recipes/category/{category_id}")
def read_recipe_by_category_api(category_id: int):
return db.get_recipe_by_category(category_id)
@app.post("/recipes")
def create_recipe_api(recipe_post: Recipe):
# שימוש ב-dict() על ה-BaseModel הופך אותו למילון עבור ה-DB
result = db.add_recipe(recipe_post.dict())
return result
@app.put("/recipes/update/{recipe_id}")
def update_recipe_api(recipe_update: Recipe,recipe_id: int):
result = db.update_recipe(recipe_update.dict(),recipe_id)
return result
@app.delete("/recipes/{recipe_id}")
def delete_recipe_api(recipe_id: int):
result = db.delete_recipe(recipe_id)
return result
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)