Build a dynamic recipe creator using OpenAI’s GPT-4 model that generates chef-quality recipes based on user-provided ingredients.
Build a dynamic recipe creator using OpenAI’s GPT-4 model. Enter a list of ingredients, and the application returns a chef-quality recipe tailored to your inputs.
Create recipe_gen() to format messages for GPT-4 and request a chat completion.
Copy
Ask AI
from openai import OpenAIclient = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))def recipe_gen(ingredients: list[str]) -> str: messages = [] # Add each ingredient as a user message for ing in ingredients: messages.append({"role": "user", "content": ing}) # Instruct the model messages.extend([ {"role": "system", "content": "Provide a concise, structured recipe."}, { "role": "assistant", "content": "You are a professional chef. Generate a detailed recipe using the above ingredients." } ]) response = client.chat.completions.create( model="gpt-4", messages=messages, max_tokens=400, temperature=0.8 ) return response.choices[0].message.content
$ python recipe_generator.pyEnter an ingredient (or 'done' to finish): applesEnter an ingredient (or 'done' to finish): grapesEnter an ingredient (or 'done' to finish): chickenEnter an ingredient (or 'done' to finish): chocolateEnter an ingredient (or 'done' to finish): done=== Generated Recipe ===Chocolate-Glazed Chicken with Apple & Grape CompoteIngredients:- 4 boneless chicken breasts- 2 apples, peeled & diced- 1 cup grapes, halved- 100g dark chocolate, melted- 1 tbsp olive oil- 1 tsp balsamic vinegar- 1 tsp honey- Salt & pepper to tasteInstructions:1. Season chicken with salt and pepper.2. Sear in olive oil over medium-high heat until cooked through.3. Mix melted chocolate, vinegar, and honey; brush onto chicken.4. Sauté apples in butter with brown sugar until soft. Add grapes and simmer 3–4 min.5. Plate chicken and top with fruit compote. Serve warm.