import osimport openaiimport panel as pn# Initialize Panel extensionpn.extension()# Configure your OpenAI API key from environment variableopenai.api_key = os.getenv("OPENAI_API_KEY")# Or hardcode your key (not recommended for production):# openai.api_key = "YOUR_API_KEY"
Storing your API key in an environment variable keeps it secure. Avoid committing secrets to version control.
Hardcoding your API key in source code can expose it publicly. Use environment variables or secret managers.
Define a reusable function that sends the full conversation history to the OpenAI GPT-3.5 Turbo model and returns the assistant’s reply.
Copy
Ask AI
def get_chat_completion(messages): """ Sends a list of message dicts to OpenAI and returns the assistant response. """ response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=messages ) return response.choices[0].message.content
We steer the chatbot’s behavior using a detailed system prompt. This includes greetings, order flow, and a complete menu. Use a Markdown table for clarity and SEO.
Copy
Ask AI
bot_instructions = """You are BurgerBot, an automated assistant for Burger Bliss. 1. Greet the customer.2. Collect the full order.3. Ask if it’s pickup or delivery.4. Summarize the order and confirm.5. If delivery, request the address.6. Collect payment.Respond in a friendly, short conversational style."""
---## 5. Building the UI with PanelInitialize the conversation context and Panel widgets. Bind the “Chat” button to our `collect_messages` function.```python# Initialize statepanels = []context = [{'role': 'system', 'content': bot_instructions}]# Create input widget and buttoninp = pn.widgets.TextInput(value="", placeholder="Type your message here...")button_conversation = pn.widgets.Button(name="Chat", button_type="primary")# Bind callbackinteractive_conversation = pn.bind(collect_messages, button_conversation)# Assemble the dashboard layoutdashboard = pn.Column( pn.pane.Markdown("## 🍔 Burger Bliss Chatbot"), inp, pn.Row(button_conversation), pn.panel(interactive_conversation, loading_indicator=True, height=400),)# Display the UIdashboard.show()```text---## 6. Example Conversation & Inspecting ContextAfter launching the dashboard, try these sample exchanges:1. “I want to order a chicken burger.” 2. “Spicy Crispy Chicken Burger.” 3. “Can I have the bill please?” 4. “I am done.” 5. “What’s the total?” 6. “Delivery”To inspect the stored message history:```python# In a separate cell, print the contextprint(context)```textYou’ll see a list of dictionaries:```python[ {'role': 'system', 'content': '...bot instructions...'}, {'role': 'assistant', 'content': 'Hi! Welcome to Burger Bliss!'}, {'role': 'user', 'content': 'I want to order a chicken burger.'}, {'role': 'assistant', 'content': 'Great choice! Which chicken burger would you like?'}, ...]
This history enables the model to maintain context across turns, crucial for coherent, multi-step conversations.