CoolFace
Apppublic

bobcatinabox/criteriabuilder

sourceHugging Facemitupdated 2y agoView on Hugging Face
0likes
app.py143 linesDownload Raw Back to root
1import openai2import gradio as gr3import requests4import json5import shutil6 7# Set your OpenAI API key here8OPENAI_API_KEY = "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"9openai.api_key = OPENAI_API_KEY10 11# URL of criteria.json12CRITERIA_JSON_URL = "https://bobcatinabox.com/myboxes/published_data/criteria.json"13 14# Global variables15bot_level = 116initial_criteria = ""17address_id = None18conversation_history = []19 20def load_initial_criteria():21    global bot_level, initial_criteria, address_id22    try:23        headers = {24            "Cache-Control": "no-cache"25        }26        response = requests.get(CRITERIA_JSON_URL, headers=headers)27        response.raise_for_status()28        data = response.json()29 30        address_id = data.get("address_id")31        bot_level = int(data.get("bot_level", 1))32        initial_criteria = data.get("criteria", "")33        print(f"Loaded bot_level: {bot_level}, initial_criteria: {initial_criteria}")34 35    except requests.exceptions.RequestException as e:36        print(f"Error fetching criteria: {e}")37        address_id = None38        bot_level = 139        initial_criteria = ""40        41load_initial_criteria()  # Ensure we always load the latest criteria42 43# Function to generate requisition criteria, follow-up question, and bot image44def generate_requisition_criteria(input_text):45    global bot_level, conversation_history46 47    # Append the new user input to the conversation history48    conversation_history.append({"role": "user", "content": input_text})49 50    # Generate requisition criteria51    try:52        response = openai.ChatCompletion.create(53            model="gpt-3.5-turbo",54            messages=[55                {"role": "system", "content": "You are an automated shopping robot responsible for finding products on the web that match user inputs. Generate detailed product selection criteria based on the user's preferences."},56                {"role": "system", "content": "Ensure the criteria are specific and actionable for an autonomous shopping bot to use in product searches."}57            ] + conversation_history,58            max_tokens=15059        )60        requisition_criteria = response.choices[0].message['content'].strip()61    except openai.error.OpenAIError as e:62        return "", f"Error: Failed to generate criteria. {e}", ""63 64    # Generate follow-up question65    try:66        follow_up_response = openai.ChatCompletion.create(67            model="gpt-3.5-turbo",68            messages=[69                {"role": "system", "content": "You are an expert assistant helping to finalize product requisition details. Based on the current criteria, ask a follow-up question to gather more specific information or clarify any ambiguities."},70                {"role": "user", "content": requisition_criteria}71            ],72            max_tokens=10073        )74        follow_up_question = follow_up_response.choices[0].message['content'].strip()75    except openai.error.OpenAIError as e:76        follow_up_question = f"Error generating follow-up question: {e}"77 78    # Increment bot level each time this function is called79    bot_level += 180 81    # Add the assistant's responses to the conversation history82    conversation_history.append({"role": "assistant", "content": requisition_criteria})83    conversation_history.append({"role": "assistant", "content": follow_up_question})84 85    # Generate updated bot level image86    bot_image_url = f"https://bobcatinabox.com/bot{bot_level}.png"87 88    return bot_image_url, requisition_criteria, gr.update(value=follow_up_question, visible=True)89 90# Reset function to clear conversation and bot level91def reset_criteria():92    global conversation_history, bot_level, initial_criteria93    conversation_history = []94    bot_level = 195    initial_criteria = ""96    return get_bot_image_url(bot_level), "", gr.update(value="", visible=False)97 98# Helper function for bot image URL99def get_bot_image_url(bot_level):100    return f"https://bobcatinabox.com/bot{bot_level}.png"101 102# Initialize the app with data from criteria.json103load_initial_criteria()104 105# Gradio interface106with gr.Blocks() as interface:107    # Add the static welcome message at the top of the page108    with gr.Row():109        with gr.Column(scale=3):110            static_text = gr.Markdown("""111                # Hello there! ๐ŸŽ‰  112                I'm your trusty shopping bot.  113                I'm here to find weird, wonderful stuff with you.  114                The more details you give me โ€” the better I can make your surprises.  115                Level me up! Type in what you're dreaming of, let me work my magic. โœจ๐Ÿ”ง116            """)117        with gr.Column(scale=1):118            bot_image_display = gr.Image(value=get_bot_image_url(bot_level), label="Bot Level")119 120    with gr.Row():121        with gr.Column():122            follow_up_textbox = gr.Textbox(label="Follow-Up Question", value="", visible=False, elem_id="followup-question")123            input_text = gr.Textbox(label="Message your bot...", placeholder="Example: length of rubber hose", elem_id="product-input", lines=5, max_lines=5)124            submit_button = gr.Button("Submit")125            reset_button = gr.Button("Reset")126 127        with gr.Column():128            output_text = gr.Textbox(label="Product Selection Criteria", value=initial_criteria, elem_id="selection-criteria")129 130    # Event triggers131    submit_button.click(132        fn=generate_requisition_criteria,133        inputs=input_text,134        outputs=[bot_image_display, output_text, follow_up_textbox]135    )136 137    reset_button.click(138        fn=reset_criteria,139        outputs=[bot_image_display, output_text, follow_up_textbox]140    )141 142interface.launch()143