File size: 1,871 Bytes
88a9229
 
 
eea3f86
 
88a9229
eea3f86
6594b81
eea3f86
6594b81
 
 
 
 
eea3f86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6594b81
eea3f86
6594b81
 
eea3f86
6594b81
 
eea3f86
 
 
6594b81
 
 
eea3f86
 
6594b81
 
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
import gradio as gr
from transformers import pipeline

# Load GPT-2 generator
generator = pipeline("text-generation", model="gpt2", max_length=200)

# Chat function
def chat(user_message, history):
    # Build context string
    context = ""
    for turn in history:
        context += f"User: {turn[0]}\nBot: {turn[1]}\n"
    context += f"User: {user_message}\nBot:"

    # Print context for debugging (will also be in trace box)
    print("----- TRACE: Prompt to LLM -----")
    print(context)
    print("---------------------------------")

    # Generate raw output
    raw_output = generator(context, max_length=len(context.split()) + 50, do_sample=True, temperature=0.7)[0]['generated_text']

    print("----- TRACE: Raw LLM output -----")
    print(raw_output)
    print("---------------------------------")

    # Extract final reply
    if "Bot:" in raw_output:
        reply = raw_output.split("Bot:")[-1].split("\n")[0].strip()
    else:
        reply = raw_output[len(context):].strip()

    # Build trace text
    trace_text = (
        f"πŸ“„ Prompt sent to LLM:\n\n{context}\n\n"
        f"⚑ Raw LLM output:\n\n{raw_output}\n\n"
        f"βœ… Final extracted reply:\n\n{reply}"
    )

    # Update history
    history.append((user_message, reply))
    return history, history, trace_text

with gr.Blocks() as demo:
    gr.Markdown("<h1 style='text-align: center;'>πŸ’¬ Conversational Agent with Trace</h1>")

    chatbot = gr.Chatbot()
    msg = gr.Textbox(placeholder="Type your message and press Enter...")

    trace_box = gr.Textbox(label="🧐 Trace Logs (for debugging)", lines=15)

    clear = gr.Button("Clear Chat")

    msg.submit(chat, [msg, chatbot], [chatbot, chatbot, trace_box])
    clear.click(lambda: ([], [], ""), None, [chatbot, chatbot, trace_box], queue=False)

demo.launch()