File size: 4,906 Bytes
8bed67e
8e10b86
8bed67e
 
 
 
 
 
8e10b86
8bed67e
 
8e10b86
8bed67e
 
 
 
 
 
 
 
 
8e10b86
 
 
 
 
 
8bed67e
8e10b86
8bed67e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e10b86
8bed67e
8e10b86
8bed67e
8e10b86
 
8bed67e
8e10b86
9c1d333
6619686
8bed67e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e10b86
 
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
import json
import gradio as gr
import os
from huggingface_hub import InferenceClient, login
from image_agent import init_stored_image_agent, stored_images
from dynamic_image_agent import main
from mulitagents import define_multi_agent
from nsfw_detection import classify_image_if_nsfw

login(os.environ.get('HF_TOKEN'))
os.environ["OPENAI_API_KEY"] = os.environ.get('OPENAI_API_KEY')

# --- Global state ---
active_agent = None  # will store which agent is currently selected

def init_and_extend_messages(system_msg: object, history: list[dict[str, str]]):
    messages = [system_msg]
    messages.extend(history)
    return messages

# --- Respond function ---
def respond(
    message,
    history: list[dict[str, str]],
    system_message,
    max_tokens,
    temperature,
    top_p
):
    """Routes the user message to the active agent."""
    global active_agent

    if not active_agent:
        return "⚠️ Please select an agent before chatting."



    try:
        # Route message to correct agent
        if active_agent == "stored":
            response = init_stored_image_agent().run(
                f"""
                {message}
                """,
                images=stored_images
            )
        elif active_agent == "dynamic":
            json_response = main()
            print("JSON RESPONSE:", json_response)
            if isinstance(json_response, str):
                return json_response
            else:
                try:
                    response = json.dumps(json_response, indent=4)
                    return response
                except (json.JSONDecodeError, TypeError):
                    # JSONDecodeError for invalid JSON format in a string
                    # TypeError if the input is not a string or bytes-like object
                    print("Error parsing json response:", json_response)
                    return "Error generating response"
        elif active_agent == "multi":
            manager_agent = define_multi_agent()
            manager_agent.visualize()

            json_response = manager_agent.run(f"""{message}""")

            manager_agent.python_executor.state["fig"]
            if isinstance(json_response, str):
                response = json_response
                return response
            else:
                try:
                    response = json.dumps(json_response, indent=4)
                    return response
                except (json.JSONDecodeError, TypeError):
                    # JSONDecodeError for invalid JSON format in a string
                    # TypeError if the input is not a string or bytes-like object
                    print("Error parsing json response:", json_response)
                    return "Error generating response"
        elif active_agent == "nsfw check":
            json_response = classify_image_if_nsfw(message)
            response = json.dumps(json_response, indent=4)
            return response
        else:
            response = f"Unknown agent selected."
    except Exception as e:
        print("Exception:", str(e))

        response = f"⚠️ Error: {e}"

    return response


# --- Button Handlers ---
def use_stored_image_agent():
    global active_agent
    active_agent = "stored"
    return "✅ Switched to Stored Image Agent."


def use_dynamic_image_agent():
    global active_agent
    active_agent = "dynamic"
    return "✅ Switched to Dynamic Image Agent."


def use_multi_agent():
    global active_agent
    active_agent = "multi"
    return "✅ Switched to Multi-Agent mode."


def use_nsfw_check():
    global active_agent
    active_agent = "nsfw check"
    classify_image_if_nsfw("https://static.api4.ai/api4.ai/nsfw/demo-pic-1.jpg")
    return "✅ Switched to NSFW Check mode."


# --- Chat Interface ---
chatbot = gr.ChatInterface(
    fn=respond,
    type="messages",
    additional_inputs=[]
)

# --- Layout ---
with gr.Blocks() as demo:

    chatbot.render()
    gr.Markdown("### 🧩 Choose an Agent:")
    with gr.Row():
        stored_img_button = gr.Button("Checked Stored Superheros", variant="secondary")
        dynamic_img_button = gr.Button("Dynamically look for superheros", variant="primary")
        multi_agent_button = gr.Button("Search superhero's using multiple agents", variant="secondary")
        check_nsfw_button = gr.Button("NSFW Check on Image", variant="stop")

    # Display agent switch confirmation message
    status_box = gr.Textbox(label="Agent Status", interactive=False)

    stored_img_button.click(fn=use_stored_image_agent, inputs=None, outputs=status_box)
    dynamic_img_button.click(fn=use_dynamic_image_agent, inputs=None, outputs=status_box)
    multi_agent_button.click(fn=use_multi_agent, inputs=None, outputs=status_box)
    check_nsfw_button.click(fn= use_nsfw_check, inputs=None, outputs=status_box)

# --- Run app ---
if __name__ == "__main__":
    demo.launch()