forked from Puneethnitc/Cooking-Assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
227 lines (177 loc) Β· 5.52 KB
/
main.py
File metadata and controls
227 lines (177 loc) Β· 5.52 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import os
import json
import requests
from dotenv import load_dotenv
from pydanticLayer import Recipe, validate_recipe
load_dotenv()
API_KEY = os.getenv("API_KEY")
URL = "https://openrouter.ai/api/v1/chat/completions"
MODEL = "meta-llama/llama-3.1-70b-instruct" # upgraded for reliable JSON
# =========================
# πΉ LLM Call
# =========================
def call_llm(prompt):
response = requests.post(
URL,
headers={
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
},
json={
"model": MODEL,
"messages": [{"role": "user", "content": prompt}],
"temperature": 0.3,
"max_tokens": 800
},
timeout=30
)
if response.status_code != 200:
raise Exception(f"LLM Error: {response.text}")
return response.json()["choices"][0]["message"]["content"]
# =========================
# πΉ Prompt Builder
# =========================
def build_prompt(user_input, state):
return f"""
You are an intelligent cooking assistant.
Your job:
- Understand the user's request
- Decide how to respond
If user wants:
1. Recipe generation or modification β return STRICT JSON
2. Explanation or question β return plain text
IMPORTANT:
- JSON must follow schema exactly
- Do NOT mix JSON and text
- Keep responses concise
Schema:
{{
"dish_name": string,
"ingredients": [
{{
"name": string,
"quantity": string,
"substitute": string or null
}}
],
"steps": [
{{
"step_number": integer,
"instruction": string
}}
],
"cooking_time": string,
"difficulty": "easy" | "medium" | "hard"
}}
Current state:
Dish: {state["dish"]}
Constraints: {state["constraints"]}
Recipe: {state["recipe"]}
User input:
{user_input}
"""
# =========================
# πΉ Output Helpers
# =========================
def clean_llm_output(raw_output: str) -> str:
raw_output = raw_output.strip()
if raw_output.startswith("```"):
raw_output = raw_output.replace("```json", "").replace("```", "")
return raw_output.strip()
def extract_json(text: str) -> str:
start = text.find("{")
end = text.rfind("}") + 1
if start == -1 or end == 0:
raise ValueError("No JSON object found in output")
return text[start:end]
def print_recipe(recipe: Recipe):
print(f"\nπ½οΈ {recipe.dish_name}")
print(f"β±οΈ Cooking time: {recipe.cooking_time} | Difficulty: {recipe.difficulty}")
print("\nπ¦ Ingredients:")
for ing in recipe.ingredients:
sub = f" (sub: {ing.substitute})" if ing.substitute else ""
print(f" - {ing.quantity} {ing.name}{sub}")
print("\nπ Steps:")
for step in recipe.steps:
print(f" {step.step_number}. {step.instruction}")
print()
# =========================
# πΉ Validation with Retry
# =========================
def get_valid_recipe(prompt, state, max_retries=2):
current_prompt = prompt
for attempt in range(max_retries + 1):
print(f"\n Attempt {attempt + 1}")
raw_output = call_llm(current_prompt)
cleaned_output = clean_llm_output(raw_output)
# Try to extract JSON even if model added surrounding text
try:
json_str = extract_json(cleaned_output)
except ValueError:
# No JSON found β treat as plain text response
return cleaned_output
recipe, error = validate_recipe(json_str)
if recipe:
print("β
β
β
Valid recipe obtained")
return recipe
print("βββ Validation failed:")
print(error)
current_prompt = f"""
Your previous response was invalid.
Error:
{error}
Fix the JSON and return ONLY valid JSON. No extra text, no markdown fences.
{prompt}
"""
return None
# =========================
# πΉ Output Handler
# =========================
def handle_output(output, state):
if output is None:
print("AI: Sorry, I couldn't generate a valid response after multiple attempts.")
return
if isinstance(output, Recipe):
state["recipe"] = output.dict()
state["dish"] = output.dish_name
print_recipe(output)
return
if isinstance(output, str):
output = output.strip()
if output.startswith("{"):
try:
cleaned = extract_json(output)
recipe, error = validate_recipe(cleaned)
if recipe:
state["recipe"] = recipe.dict()
state["dish"] = recipe.dish_name
print_recipe(recipe)
else:
print(f"AI: Sorry, something went wrong with the recipe format.\n{error}")
except ValueError as e:
print(f"AI: Sorry, something went wrong. {e}")
else:
print("\nAI:", output)
# =========================
# πΉ Chatbot Loop (CLI only)
# =========================
if __name__ == "__main__":
state = {
"dish": None,
"recipe": None,
"constraints": []
}
print("\n" + "=" * 40)
print(" AI COOKING CHATBOT ")
print("=" * 40)
print("Ask anything about cooking π³")
print("Type 'exit' to quit\n")
while True:
user_input = input("You: ").strip()
if user_input.lower() in ["exit", "quit"]:
print("AI: Goodbye π")
break
state["constraints"].append(user_input)
prompt = build_prompt(user_input, state)
output = get_valid_recipe(prompt, state)
handle_output(output, state)