# Acknowledgement: This demo code is adapted from the original Hugging Face Space "ContextCite"
# (https://huggingface.co/spaces/contextcite/context-cite).
import os
from enum import Enum
from dataclasses import dataclass
from typing import Dict, List, Any, Optional
import gradio as gr
import numpy as np
import spaces
import nltk
import base64
import traceback
from src.utils import split_into_sentences as split_into_sentences_utils
# --- AttnTrace imports (from app_full.py) ---
from src.models import create_model
from src.attribution import AttnTraceAttribution
from src.prompts import wrap_prompt
from gradio_highlightedtextbox import HighlightedTextbox
from examples import run_example_1, run_example_2, run_example_3, run_example_4, run_example_5, run_example_6
from functools import partial
from nltk.tokenize import sent_tokenize
# Load original app constants
APP_TITLE = '
AttnTrace is an efficient context traceback method for long contexts (e.g., full papers). It is over 15Γ faster than the state-of-the-art context traceback method TracLLM. Compared to previous attention-based approaches, AttnTrace is more accurate, reliable, and memory-efficient.
""", elem_classes="feature-highlights")
# Feature highlights
gr.Markdown("""
AttnTrace can be used in many real-world applications, such as tracing back to:
- π prompt injection instructions that manipulate LLM-generated paper reviews.
- π» malicious comment & code hiding in the codebase that misleads the AI coding assistant.
- π€ malicious instructions that mislead the action of the LLM agent.
- π source texts in the context from an AI summary.
- π evidence that supports the LLM-generated answer for a question.
- β misinformation (corrupted knowledge) that manipulates LLM output for a question.
- And a lot more...
""", elem_classes="feature-highlights")
# Example buttons with topic-relevant images - moved here for better positioning
gr.Markdown("### π Try These Examples!", elem_classes="example-title")
with gr.Row(elem_classes=["example-button-container"]):
with gr.Column(scale=1):
example_1_btn = gr.Button(
"π Prompt Injection Attacks in AI Paper Review",
elem_classes=["example-button", "example-paper"],
elem_id="example_1_button",
scale=None,
size="sm"
)
with gr.Column(scale=1):
example_2_btn = gr.Button(
"π» Malicious Comments & Code in Codebase",
elem_classes=["example-button", "example-movie"],
elem_id="example_2_button"
)
with gr.Column(scale=1):
example_3_btn = gr.Button(
"π€ Malicious Instructions Misleading the LLM Agent",
elem_classes=["example-button", "example-code"],
elem_id="example_3_button"
)
with gr.Row(elem_classes=["example-button-container"]):
with gr.Column(scale=1):
example_4_btn = gr.Button(
"π Source Texts for an AI Summary",
elem_classes=["example-button", "example-paper-alt"],
elem_id="example_4_button"
)
with gr.Column(scale=1):
example_5_btn = gr.Button(
"π Evidence that Support Question Answering",
elem_classes=["example-button", "example-movie-alt"],
elem_id="example_5_button"
)
with gr.Column(scale=1):
example_6_btn = gr.Button(
"β Misinformation (Corrupted Knowledge) in Question Answering",
elem_classes=["example-button", "example-code-alt"],
elem_id="example_6_button"
)
state = gr.State(
value=clear_state()
)
# Create tabs for Demo and Configuration
with gr.Tabs() as main_tabs:
# Demo Tab
with gr.Tab("Demo", id="demo_tab"):
gr.Markdown(
"Enter your context and instruction below to try out AttnTrace! You can also click on the example buttons above to load pre-configured examples."
)
gr.Markdown(
'**Color Legend for Context Traceback (by ranking):**
Red = 1st (most important) |
Orange = 2nd |
Golden = 3rd |
Yellow = 4th-5th |
Light = 6th+'
)
# Top section: Wide Context box with tabs
with gr.Row():
with gr.Column(scale=1):
with gr.Tabs() as basic_context_tabs:
with gr.TabItem("Context", id=0):
basic_context_box = gr.Textbox(
placeholder="Enter context...",
show_label=False,
value="",
lines=6,
max_lines=6,
elem_id="basic_context_box",
autoscroll=False,
)
with gr.TabItem("Context with highlighted traceback results", id=1, visible=True) as basic_sources_in_context_tab:
basic_sources_in_context_box = HighlightedTextbox(
value=[("Click on a sentence in the response below to see highlighted traceback results here.", None)],
show_legend_label=False,
show_label=False,
show_legend=False,
interactive=False,
elem_id="basic_sources_in_context_box",
)
# Error messages
basic_generate_error_box = HighlightedTextbox(
show_legend_label=False,
show_label=False,
show_legend=False,
visible=False,
interactive=False,
container=False,
)
# Bottom section: Left (instruction + button + response), Right (response selection)
with gr.Row(equal_height=True):
# Left: Instruction + Button + Response
with gr.Column(scale=1):
basic_query_box = gr.Textbox(
label="Instruction",
placeholder="Enter an instruction...",
value="",
lines=3,
max_lines=3,
)
unified_response_button = gr.Button(
"Generate/Use Response",
variant="primary",
size="lg"
)
response_input_box = gr.Textbox(
label="Response (Editable)",
placeholder="Response will appear here after generation, or type your own response for traceback...",
lines=8,
max_lines=8,
info="Leave empty and click button to generate from LLM, or type your own response to use for traceback"
)
# Right: Response for attribution selection
with gr.Column(scale=1):
basic_response_box = gr.HighlightedText(
label="Click to select text for traceback!",
value=[("Click the 'Generate/Use Response' button on the left to see response text here for traceback analysis.", None)],
interactive=False,
combine_adjacent=False,
show_label=True,
show_legend=False,
elem_id="basic_response_box",
visible=True,
)
# Button for full response traceback
full_response_traceback_button = gr.Button(
"π Traceback Entire Response",
variant="secondary",
size="sm"
)
# Hidden error box and dummy elements
basic_attribute_error_box = HighlightedTextbox(
show_legend_label=False,
show_label=False,
show_legend=False,
visible=False,
interactive=False,
container=False,
)
dummy_basic_sources_box = gr.Textbox(
visible=False, interactive=False, container=False
)
# Configuration Tab
with gr.Tab("Config", id="config_tab"):
gr.Markdown("## βοΈ AttnTrace Configuration")
gr.Markdown("Configure the traceback analysis parameters to customize how AttnTrace processes your context and generates results.")
with gr.Row():
with gr.Column(scale=1):
explanation_level_dropdown = gr.Dropdown(
choices=["sentence", "paragraph", "text segment"],
value="sentence",
label="Explanation Level",
info="How to segment the context for traceback analysis"
)
with gr.Column(scale=1):
top_k_dropdown = gr.Dropdown(
choices=["3", "5", "10"],
value="3",
label="Top-N Value",
info="Number of most important text segments to highlight"
)
with gr.Row():
with gr.Column(scale=1):
B_slider = gr.Slider(
minimum=1,
maximum=100,
value=30,
step=5,
label="B Parameter",
info="Number of subsamples (higher = more accurate but slower)"
)
with gr.Column(scale=1):
q_slider = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.4,
step=0.1,
label="Ο Parameter",
info="Sub-sampling ratio (0.1-1.0)"
)
with gr.Row():
with gr.Column(scale=1):
apply_config_button = gr.Button(
"Apply Configuration",
variant="primary",
size="lg"
)
with gr.Column(scale=2):
config_status_text = gr.Textbox(
label="Configuration Status",
value="Ready to apply configuration",
interactive=False,
lines=2
)
gr.Markdown("### π Current Configuration")
gr.Markdown("""
- **Explanation Level**: Determines how the context is segmented for analysis
- `sentence`: Analyze at sentence level (recommended for most cases)
- `paragraph`: Analyze at paragraph level (good for longer documents)
- `text segment`: Analyze at the level of 100-word text segments (ideal for non-standard document formats)
- **Top-N Value**: Number of most important text segments to highlight in results
- Higher values show more context but may be less focused
- Lower values provide more focused results but may miss some context
- **B Parameter**: Number of subsamples
- Higher values (50-100): More thorough analysis but slower
- Lower values (10-30): Faster analysis but may miss some important segments
- Default: 30 (good balance of speed and accuracy)
- **Ο Parameter**: Sub-sampling ratio (0.1-1.0)
**Note**: Configuration changes will take effect immediately for new traceback operations.
""")
gr.Markdown("### π Model Information")
gr.Markdown(f"""
- **Current Model**: {DEFAULT_MODEL_PATH}
- **Max Tokens**: {get_max_tokens(DEFAULT_MODEL_PATH):,}
- **Device**: CUDA (GPU accelerated)
""")
# Only a single (AttnTrace) method and model in this simplified version
def basic_clear_state():
state = clear_state()
return (
"", # basic_context_box
"", # basic_query_box
"", # response_input_box
gr.update(value=[("Click the 'Generate/Use Response' button above to see response text here for traceback analysis.", None)]), # basic_response_box - keep visible
gr.update(selected=0), # basic_context_tabs - switch to first tab
state,
)
# Defining behavior of various interactions for the demo tab only
def handle_demo_tab_selection(evt: gr.SelectData):
"""Handle tab selection - only clear state when switching to demo tab"""
if evt.index == 0: # Demo tab
return basic_clear_state()
else: # Configuration tab - no state change needed
return (
gr.update(), # basic_context_box
gr.update(), # basic_query_box
gr.update(), # response_input_box
gr.update(), # basic_response_box
gr.update(), # basic_context_tabs
gr.update(), # state
)
main_tabs.select(
fn=handle_demo_tab_selection,
inputs=[],
outputs=[
basic_context_box,
basic_query_box,
response_input_box,
basic_response_box,
basic_context_tabs,
state,
],
)
for component in [basic_context_box, basic_query_box]:
component.change(
basic_update,
[basic_context_box, basic_query_box, state],
[
basic_response_box,
basic_context_tabs,
state,
],
)
# Example button event handlers - now update both UI and state
outputs_for_examples = [
basic_context_box,
basic_query_box,
state,
response_input_box,
basic_response_box,
basic_context_tabs,
]
example_1_btn.click(
fn=partial(load_an_example, run_example_1),
inputs=[state],
outputs=outputs_for_examples
)
example_2_btn.click(
fn=partial(load_an_example, run_example_2),
inputs=[state],
outputs=outputs_for_examples
)
example_3_btn.click(
fn=partial(load_an_example, run_example_3),
inputs=[state],
outputs=outputs_for_examples
)
example_4_btn.click(
fn=partial(load_an_example, run_example_4),
inputs=[state],
outputs=outputs_for_examples
)
example_5_btn.click(
fn=partial(load_an_example, run_example_5),
inputs=[state],
outputs=outputs_for_examples
)
example_6_btn.click(
fn=partial(load_an_example, run_example_6),
inputs=[state],
outputs=outputs_for_examples
)
unified_response_button.click(
fn=lambda: None,
inputs=[],
outputs=[],
js=get_scroll_js_code("basic_response_box"),
)
basic_response_box.change(
fn=lambda: None,
inputs=[],
outputs=[],
js=get_scroll_js_code("basic_sources_in_context_box"),
)
# Add immediate tab switch on response selection
def immediate_tab_switch():
return (
gr.update(value=[("π Processing traceback... Please wait...", None)]), # Show progress message
gr.update(selected=1), # Switch to annotation tab immediately
)
basic_response_box.select(
fn=immediate_tab_switch,
inputs=[],
outputs=[basic_sources_in_context_box, basic_context_tabs],
queue=False, # Execute immediately without queue
)
basic_response_box.select(
fn=basic_get_scores_and_sources,
inputs=[basic_response_box, state],
outputs=[
basic_sources_in_context_box,
basic_context_tabs,
basic_sources_in_context_tab,
dummy_basic_sources_box,
basic_attribute_error_box,
state,
],
show_progress="full",
)
basic_response_box.select(
fn=basic_update_highlighted_response,
inputs=[state],
outputs=[basic_response_box, state],
)
# Full response traceback button
full_response_traceback_button.click(
fn=immediate_tab_switch,
inputs=[],
outputs=[basic_sources_in_context_box, basic_context_tabs],
queue=False, # Execute immediately without queue
)
full_response_traceback_button.click(
fn=basic_get_scores_and_sources_full_response,
inputs=[state],
outputs=[
basic_sources_in_context_box,
basic_context_tabs,
basic_sources_in_context_tab,
dummy_basic_sources_box,
basic_attribute_error_box,
state,
],
show_progress="full",
)
dummy_basic_sources_box.change(
fn=lambda: None,
inputs=[],
outputs=[],
js=get_scroll_js_code("basic_sources_in_context_box"),
)
# Unified response handler
unified_response_button.click(
fn=unified_response_handler,
inputs=[response_input_box, state],
outputs=[state, response_input_box, basic_response_box, basic_generate_error_box]
)
# Configuration update handler
apply_config_button.click(
fn=update_configuration,
inputs=[explanation_level_dropdown, top_k_dropdown, B_slider, q_slider],
outputs=[config_status_text]
)
# gr.Markdown(
# "Please do not interact with elements while generation/attribution is in progress. This may cause errors. You can refresh the page if you run into issues because of this."
# )
demo.launch(show_api=False, share=True)