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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uuid
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from langgraph.graph import MessagesState, StateGraph, START
|
| 5 |
+
from langgraph.checkpoint.memory import MemorySaver
|
| 6 |
+
from langchain_groq import ChatGroq
|
| 7 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 8 |
+
|
| 9 |
+
# Get API key from environment variables
|
| 10 |
+
GROQ_API_KEY = os.environ['GROQ_API_KEY']
|
| 11 |
+
|
| 12 |
+
# Initialize the Groq LLM
|
| 13 |
+
llm = ChatGroq(groq_api_key=GROQ_API_KEY, model_name="llama3-8b-8192")
|
| 14 |
+
|
| 15 |
+
# Helper functions
|
| 16 |
+
def get_original_text(messages):
|
| 17 |
+
for msg in messages:
|
| 18 |
+
if isinstance(msg, HumanMessage) and "Rewrite this text in" in msg.content:
|
| 19 |
+
return msg.content.split("tone: ")[1]
|
| 20 |
+
return ""
|
| 21 |
+
|
| 22 |
+
def get_current_text_and_tone(messages):
|
| 23 |
+
for msg in reversed(messages):
|
| 24 |
+
if isinstance(msg, AIMessage):
|
| 25 |
+
return msg.content, "Unknown" # Simplified since we now strip metadata
|
| 26 |
+
return None, None
|
| 27 |
+
|
| 28 |
+
def extract_display_text(message):
|
| 29 |
+
return message.strip()
|
| 30 |
+
|
| 31 |
+
# Assistant node with clean output
|
| 32 |
+
def assistant(state: MessagesState):
|
| 33 |
+
messages = state["messages"]
|
| 34 |
+
latest_msg = messages[-1].content
|
| 35 |
+
|
| 36 |
+
if "Rewrite this text in" in latest_msg:
|
| 37 |
+
tone = latest_msg.split(" in ")[1].split(" tone:")[0]
|
| 38 |
+
text = latest_msg.split("tone: ")[1]
|
| 39 |
+
prompt = f"Rewrite the following legal text related to special education in California in a {tone} tone, ensuring it remains compliant with state and federal regulations. Only return the rewritten text, without any explanation or prefix.\n\nText: {text}"
|
| 40 |
+
response = llm.invoke(prompt)
|
| 41 |
+
rewritten_text = response.content.strip()
|
| 42 |
+
return {"messages": [AIMessage(content=rewritten_text)]}
|
| 43 |
+
|
| 44 |
+
elif latest_msg == "regenerate":
|
| 45 |
+
original_text = get_original_text(messages)
|
| 46 |
+
if not original_text:
|
| 47 |
+
return {"messages": [AIMessage(content="Error: Original text not found.")]}
|
| 48 |
+
_, current_tone = get_current_text_and_tone(messages)
|
| 49 |
+
if not current_tone:
|
| 50 |
+
return {"messages": [AIMessage(content="Error: Current tone not found.")]}
|
| 51 |
+
prompt = f"Rewrite the following legal text related to special education in California in a {current_tone} tone. Only return the rewritten text, without any explanation or prefix.\n\nText: {original_text}"
|
| 52 |
+
response = llm.invoke(prompt)
|
| 53 |
+
new_text = response.content.strip()
|
| 54 |
+
return {"messages": [AIMessage(content=new_text)]}
|
| 55 |
+
|
| 56 |
+
elif latest_msg.startswith("feedback:"):
|
| 57 |
+
feedback = latest_msg.split("feedback: ")[1].strip()
|
| 58 |
+
current_text, current_tone = get_current_text_and_tone(messages)
|
| 59 |
+
if not current_text or not current_tone:
|
| 60 |
+
return {"messages": [AIMessage(content="Error: Current text or tone not found.")]}
|
| 61 |
+
prompt = f"Refine the following legal text related to special education in California based on this feedback: '{feedback}'. Maintain the {current_tone} tone and ensure compliance with regulations. Only return the refined text, without any explanation or prefix.\n\nText: {current_text}"
|
| 62 |
+
response = llm.invoke(prompt)
|
| 63 |
+
refined_text = response.content.strip()
|
| 64 |
+
return {"messages": [AIMessage(content=refined_text)]}
|
| 65 |
+
|
| 66 |
+
elif latest_msg.lower() == "approve":
|
| 67 |
+
current_text, _ = get_current_text_and_tone(messages)
|
| 68 |
+
if not current_text:
|
| 69 |
+
return {"messages": [AIMessage(content="Error: No text to approve.")]}
|
| 70 |
+
return {"messages": [AIMessage(content=f"Text approved: {current_text}")]}
|
| 71 |
+
else:
|
| 72 |
+
return {"messages": [AIMessage(content="Invalid command.")]}
|
| 73 |
+
|
| 74 |
+
# Human feedback node
|
| 75 |
+
def human_feedback(state: MessagesState):
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
# Build LangGraph
|
| 79 |
+
builder = StateGraph(MessagesState)
|
| 80 |
+
builder.add_node("assistant", assistant)
|
| 81 |
+
builder.add_node("human_feedback", human_feedback)
|
| 82 |
+
builder.add_edge(START, "human_feedback")
|
| 83 |
+
builder.add_edge("human_feedback", "assistant")
|
| 84 |
+
builder.add_edge("assistant", "human_feedback")
|
| 85 |
+
memory = MemorySaver()
|
| 86 |
+
graph = builder.compile(interrupt_before=["human_feedback"], checkpointer=memory)
|
| 87 |
+
|
| 88 |
+
# Gradio logic
|
| 89 |
+
def initial_submit_fn(legal_text, initial_tone, state):
|
| 90 |
+
if state["configurable"]["thread_id"] == "1":
|
| 91 |
+
state["configurable"]["thread_id"] = str(uuid.uuid4())
|
| 92 |
+
if not legal_text.strip():
|
| 93 |
+
return "Please enter legal text.", state
|
| 94 |
+
command = f"Rewrite this text in {initial_tone} tone: {legal_text}"
|
| 95 |
+
graph.update_state(state, {"messages": [HumanMessage(content=command)]}, as_node="human_feedback")
|
| 96 |
+
for event in graph.stream(None, state, stream_mode="values"):
|
| 97 |
+
if "messages" in event:
|
| 98 |
+
rewritten_text = event["messages"][-1].content
|
| 99 |
+
display_text = extract_display_text(rewritten_text)
|
| 100 |
+
return display_text, state
|
| 101 |
+
|
| 102 |
+
def regenerate_fn(state):
|
| 103 |
+
graph.update_state(state, {"messages": [HumanMessage(content="regenerate")]}, as_node="human_feedback")
|
| 104 |
+
for event in graph.stream(None, state, stream_mode="values"):
|
| 105 |
+
if "messages" in event:
|
| 106 |
+
rewritten_text = event["messages"][-1].content
|
| 107 |
+
display_text = extract_display_text(rewritten_text)
|
| 108 |
+
return display_text, state
|
| 109 |
+
|
| 110 |
+
def submit_feedback_fn(feedback_text, state):
|
| 111 |
+
if not feedback_text.strip():
|
| 112 |
+
return "Please enter feedback.", state, ""
|
| 113 |
+
command = f"feedback: {feedback_text}"
|
| 114 |
+
graph.update_state(state, {"messages": [HumanMessage(content=command)]}, as_node="human_feedback")
|
| 115 |
+
for event in graph.stream(None, state, stream_mode="values"):
|
| 116 |
+
if "messages" in event:
|
| 117 |
+
rewritten_text = event["messages"][-1].content
|
| 118 |
+
display_text = extract_display_text(rewritten_text)
|
| 119 |
+
return display_text, state, ""
|
| 120 |
+
|
| 121 |
+
def approve_fn(state):
|
| 122 |
+
graph.update_state(state, {"messages": [HumanMessage(content="approve")]}, as_node="human_feedback")
|
| 123 |
+
for event in graph.stream(None, state, stream_mode="values"):
|
| 124 |
+
if "messages" in event:
|
| 125 |
+
confirmation = event["messages"][-1].content
|
| 126 |
+
return confirmation, state
|
| 127 |
+
|
| 128 |
+
# Gradio UI
|
| 129 |
+
with gr.Blocks(title="Legal Text Rewriter for Special Education in California") as demo:
|
| 130 |
+
state = gr.State(value={"configurable": {"thread_id": "1"}})
|
| 131 |
+
|
| 132 |
+
with gr.Column():
|
| 133 |
+
legal_text = gr.Textbox(label="Legal Text", placeholder="Enter your legal text here")
|
| 134 |
+
initial_tone = gr.Dropdown(
|
| 135 |
+
label="Initial Tone",
|
| 136 |
+
choices=["Formal", "Empathetic", "Neutral", "Strength-Based"],
|
| 137 |
+
value="Formal"
|
| 138 |
+
)
|
| 139 |
+
submit_btn = gr.Button("Submit")
|
| 140 |
+
|
| 141 |
+
rewritten_text_display = gr.Textbox(label="Rewritten Text", interactive=False)
|
| 142 |
+
gr.Markdown("")
|
| 143 |
+
|
| 144 |
+
regenerate_btn = gr.Button("Regenerate")
|
| 145 |
+
feedback_textbox = gr.Textbox(label="Feedback", placeholder="Enter feedback to refine the text")
|
| 146 |
+
submit_feedback_btn = gr.Button("Submit Feedback")
|
| 147 |
+
approve_btn = gr.Button("Approve")
|
| 148 |
+
|
| 149 |
+
# Button bindings
|
| 150 |
+
submit_btn.click(initial_submit_fn, [legal_text, initial_tone, state], [rewritten_text_display, state])
|
| 151 |
+
regenerate_btn.click(regenerate_fn, [state], [rewritten_text_display, state])
|
| 152 |
+
submit_feedback_btn.click(submit_feedback_fn, [feedback_textbox, state], [rewritten_text_display, state, feedback_textbox])
|
| 153 |
+
approve_btn.click(approve_fn, [state], [rewritten_text_display, state])
|
| 154 |
+
|
| 155 |
+
demo.launch()
|