MBG0903 commited on
Commit
d4d9e63
Β·
verified Β·
1 Parent(s): 193f9ae

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +645 -30
src/streamlit_app.py CHANGED
@@ -1,40 +1,655 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
 
 
4
  import streamlit as st
5
 
6
- """
7
- # Welcome to Streamlit!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
 
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
 
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
 
 
 
18
 
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
 
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
 
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
1
+ import os
2
+ import uuid
3
+ import tempfile
4
+ from typing import Annotated, List, TypedDict, Dict, Any
5
+
6
  import streamlit as st
7
 
8
+ from langchain_core.documents import Document
9
+ from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, ToolMessage
10
+ from langchain_core.tools import tool
11
+ from langchain_openai import ChatOpenAI, OpenAIEmbeddings
12
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
13
+
14
+ try:
15
+ from langchain_chroma import Chroma
16
+ except Exception:
17
+ from langchain_community.vectorstores import Chroma
18
+
19
+ try:
20
+ from langchain_community.tools.tavily_search import TavilySearchResults
21
+ except Exception:
22
+ TavilySearchResults = None
23
+
24
+ from langgraph.graph import StateGraph, END
25
+ from langgraph.graph.message import add_messages
26
+ from langgraph.prebuilt import ToolNode
27
+ from langgraph.checkpoint.memory import MemorySaver
28
+
29
+
30
+ st.set_page_config(
31
+ page_title="Legal Agentic AI Project",
32
+ page_icon="βš–οΈ",
33
+ layout="wide",
34
+ )
35
+
36
+
37
+ SAMPLE_CASE = '''
38
+ Case No: 2024/CR/12345
39
+ Court: District Court, US
40
+
41
+ Facts:
42
+ The defendant, Mr. Alex Carter, was charged with breach of contract dated January 15, 2023.
43
+ The plaintiff, ABC Corporation, claims that the defendant failed to deliver 1000 units of
44
+ electronic components as per the signed agreement. The contract specified delivery by March 31, 2023.
45
+
46
+ The defendant claims that due to unforeseen supply chain disruptions caused by the pandemic,
47
+ delivery was impossible. However, no force majeure clause was explicitly invoked in writing
48
+ within the stipulated 30-day notice period as mentioned in Section 12 of the contract.
49
+
50
+ The plaintiff seeks damages of Rs. 50,00,000 for business losses incurred due to delayed delivery.
51
+ The defendant argues that the damages claimed are excessive and not proven with adequate documentation.
52
+
53
+ Key Issues:
54
+ 1. Was there a valid force majeure event?
55
+ 2. Did the defendant provide proper notice?
56
+ 3. Are the damages claimed reasonable and substantiated?
57
+ 4. Was there any contributory negligence by the plaintiff?
58
+ '''
59
+
60
+
61
+ LEGAL_KNOWLEDGE_BASE = [
62
+ '''
63
+ Precedent Case: Smith v. Johnson (2022)
64
+ Court ruled that force majeure must be invoked in writing within the contractual notice period.
65
+ Failure to do so waives the right to claim force majeure defense.
66
+ Citation: [2022] 3 SCC 145
67
+ ''',
68
+ '''
69
+ Precedent Case: ABC Corp v. XYZ Ltd (2021)
70
+ In breach of contract cases, damages must be proven with documentary evidence.
71
+ Speculative damages without supporting documentation are not admissible.
72
+ The burden of proof lies with the plaintiff.
73
+ Citation: [2021] 2 BomHC 78
74
+ ''',
75
+ '''
76
+ Legal Principle: Contributory Negligence
77
+ If the plaintiff's actions contributed to the breach or losses, damages may be reduced proportionally.
78
+ Courts have recognized this principle in commercial contract disputes.
79
+ Reference: US Contract Act, 1872, Section 73
80
+ ''',
81
+ '''
82
+ Force Majeure During Pandemic
83
+ Courts have taken a nuanced view of COVID-19 as force majeure.
84
+ The invoking party must demonstrate: (1) impossibility, not mere difficulty,
85
+ (2) proper notice, and (3) mitigation efforts.
86
+ Citation: Energy Watchdog v. CERC (2020)
87
+ ''',
88
+ '''
89
+ Force Majeure Invocation - Notice Requirement
90
+ Relevant Precedent: Smith v. Johnson (2022)
91
+ Citation: [2022] 3 SCC 145
92
+ Legal Principle:
93
+ Force majeure must be invoked in writing within the contractual notice period.
94
+ Failure to comply with the notice requirement waives the right to claim force majeure defense.
95
+
96
+ Application to Current Case:
97
+ The contract specified a 30-day notice period under Section 12.
98
+ Mr. Alex Carter failed to invoke force majeure in writing within this stipulated period.
99
+ This precedent strongly supports the plaintiff's position.
100
+ ''',
101
+ '''
102
+ Burden of Proof for Damages
103
+ Relevant Precedent: ABC Corp v. XYZ Ltd (2021)
104
+ Citation: [2021] 2 BomHC 78
105
+ Legal Principle:
106
+ In breach of contract cases, damages must be proven with documentary evidence.
107
+ Speculative damages without supporting documentation are not admissible.
108
+ The burden of proof lies with the plaintiff.
109
+
110
+ Application to Current Case:
111
+ ABC Corporation claims Rs. 50,00,000 in damages.
112
+ The plaintiff must provide concrete evidence such as lost orders, financial statements,
113
+ alternative procurement costs, and documented business loss.
114
+ ''',
115
+ '''
116
+ Relevant Precedent: Energy Watchdog v. CERC (2020)
117
+ Legal Principle:
118
+ Courts apply a nuanced, three-part test for COVID-19 related force majeure claims:
119
+ 1. Impossibility, not mere difficulty or inconvenience
120
+ 2. Proper notice as per contractual terms
121
+ 3. Mitigation efforts undertaken by the affected party
122
+
123
+ Application to Current Case:
124
+ The defendant must demonstrate absolute impossibility of performance, not merely increased cost or delay.
125
+ The defendant must also show good faith mitigation efforts, such as seeking alternative suppliers.
126
+ ''',
127
+ ]
128
+
129
+
130
+ class AgentState(TypedDict):
131
+ messages: Annotated[list, add_messages]
132
+ case_text: str
133
+ final_analysis: str
134
+
135
+
136
+ def secrets_ready() -> bool:
137
+ return bool(os.getenv("OPENAI_API_KEY"))
138
+
139
+
140
+ @st.cache_resource(show_spinner=False)
141
+ def create_vectorstore(openai_key: str):
142
+ docs = [Document(page_content=doc) for doc in LEGAL_KNOWLEDGE_BASE]
143
+
144
+ text_splitter = RecursiveCharacterTextSplitter(
145
+ chunk_size=1000,
146
+ chunk_overlap=200,
147
+ )
148
+ splits = text_splitter.split_documents(docs)
149
+
150
+ embedding_model = OpenAIEmbeddings(
151
+ model="text-embedding-3-small",
152
+ api_key=openai_key,
153
+ )
154
+
155
+ persist_dir = tempfile.mkdtemp(prefix="legal_agent_chroma_")
156
+
157
+ vectorstore = Chroma.from_documents(
158
+ documents=splits,
159
+ embedding=embedding_model,
160
+ collection_name=f"legal_cases_{uuid.uuid4().hex[:8]}",
161
+ persist_directory=persist_dir,
162
+ )
163
+
164
+ return vectorstore, len(splits)
165
+
166
+
167
+ def build_legal_agent(model_name: str, temperature: float = 0.0):
168
+ openai_key = os.getenv("OPENAI_API_KEY")
169
+ tavily_key = os.getenv("TAVILY_API_KEY")
170
+
171
+ llm = ChatOpenAI(
172
+ model=model_name,
173
+ temperature=temperature,
174
+ api_key=openai_key,
175
+ )
176
+
177
+ vectorstore, chunk_count = create_vectorstore(openai_key)
178
+
179
+ @tool
180
+ def rag_search_tool(query: str) -> str:
181
+ """Search legal case documents using RAG for similar precedents and relevant information."""
182
+ docs = vectorstore.similarity_search(query, k=3)
183
+
184
+ if not docs:
185
+ return "No relevant legal precedents found in the knowledge base."
186
+
187
+ results = []
188
+ for i, doc in enumerate(docs, 1):
189
+ results.append(f"Precedent {i}:\n{doc.page_content}")
190
+
191
+ return "\n\n".join(results)
192
+
193
+ @tool
194
+ def tavily_web_search_tool(query: str) -> str:
195
+ """Search the web using Tavily for recent legal cases and legal developments."""
196
+ if not tavily_key:
197
+ return (
198
+ "Tavily web search is not configured. "
199
+ "Add TAVILY_API_KEY in Hugging Face Space secrets to enable live web search."
200
+ )
201
+
202
+ if TavilySearchResults is None:
203
+ return "Tavily package is not installed. Add tavily-python to requirements.txt."
204
+
205
+ tavily_tool = TavilySearchResults(max_results=3)
206
+ results = tavily_tool.invoke({"query": query})
207
+
208
+ if not results:
209
+ return "No web search results found."
210
+
211
+ formatted_results = []
212
+ for i, result in enumerate(results, 1):
213
+ content = result.get("content", "No content available")
214
+ url = result.get("url", "No URL")
215
+ formatted_results.append(f"Result {i}:\n{content}\nSource: {url}")
216
+
217
+ return "\n\n".join(formatted_results)
218
+
219
+ @tool
220
+ def analyze_loopholes_tool(case_summary: str) -> str:
221
+ """Analyze legal case to identify potential loopholes using LLM reasoning."""
222
+ analysis_prompt = f'''
223
+ You are a senior legal analyst. Analyze the following case and identify potential loopholes.
224
+
225
+ Case Summary:
226
+ {case_summary}
227
+
228
+ Identify:
229
+ 1. Procedural loopholes
230
+ 2. Evidentiary gaps
231
+ 3. Jurisdictional issues
232
+ 4. Statute of limitations concerns
233
+ 5. Constitutional challenges
234
+
235
+ Provide a detailed analysis with reasoning.
236
+ '''
237
+ response = llm.invoke([HumanMessage(content=analysis_prompt)])
238
+ return response.content
239
+
240
+ tools = [rag_search_tool, tavily_web_search_tool, analyze_loopholes_tool]
241
+
242
+ def agent_node(state: AgentState) -> Dict[str, Any]:
243
+ system_prompt = SystemMessage(
244
+ content=f'''
245
+ You are an expert legal analysis AI agent specializing in identifying loopholes and weaknesses in legal cases.
246
+
247
+ Case to Analyze:
248
+ {state["case_text"]}
249
+
250
+ Your Task:
251
+ Conduct a comprehensive legal analysis by:
252
+ 1. Searching for similar precedent cases using rag_search_tool
253
+ 2. Finding recent legal developments using tavily_web_search_tool
254
+ 3. Analyzing loopholes using analyze_loopholes_tool
255
+
256
+ Analysis Framework:
257
+ - Force majeure defenses and procedural requirements
258
+ - Notice requirements and timelines
259
+ - Burden of proof and evidence standards
260
+ - Contributory negligence considerations
261
+ - Damages calculation and substantiation
262
+
263
+ After gathering all information, provide a comprehensive final analysis covering:
264
+ - Case summary
265
+ - Relevant precedents found
266
+ - Current legal developments, if available
267
+ - Procedural loopholes
268
+ - Evidentiary weaknesses
269
+ - Risk assessment
270
+ - Strategic recommendations for plaintiff and defendant
271
+
272
+ Use the tools before concluding.
273
+ '''
274
+ )
275
+
276
+ llm_with_tools = llm.bind_tools(tools)
277
+ response = llm_with_tools.invoke([system_prompt] + state["messages"])
278
+ return {"messages": [response]}
279
+
280
+ def should_continue(state: AgentState) -> str:
281
+ last_message = state["messages"][-1]
282
+
283
+ if isinstance(last_message, AIMessage) and getattr(last_message, "tool_calls", None):
284
+ return "tools"
285
+
286
+ return "end"
287
+
288
+ workflow = StateGraph(AgentState)
289
+ workflow.add_node("agent", agent_node)
290
+ workflow.add_node("tools", ToolNode(tools))
291
+
292
+ workflow.set_entry_point("agent")
293
+ workflow.add_conditional_edges(
294
+ "agent",
295
+ should_continue,
296
+ {
297
+ "tools": "tools",
298
+ "end": END,
299
+ },
300
+ )
301
+ workflow.add_edge("tools", "agent")
302
+
303
+ memory = MemorySaver()
304
+ graph = workflow.compile(checkpointer=memory)
305
+
306
+ return graph, chunk_count
307
+
308
 
309
+ def run_legal_analysis(case_text: str, model_name: str, temperature: float):
310
+ graph, chunk_count = build_legal_agent(model_name, temperature)
 
311
 
312
+ thread_id = f"legal_case_{uuid.uuid4().hex[:8]}"
313
+ config = {"configurable": {"thread_id": thread_id}}
314
 
315
+ initial_state = {
316
+ "messages": [HumanMessage(content="Analyze this legal case for loopholes and weaknesses.")],
317
+ "case_text": case_text,
318
+ "final_analysis": "",
319
+ }
320
 
321
+ trace = []
322
+ final_answer = ""
 
323
 
324
+ for step_output in graph.stream(initial_state, config, stream_mode="values"):
325
+ last_message = step_output["messages"][-1]
326
 
327
+ if isinstance(last_message, AIMessage):
328
+ tool_calls = getattr(last_message, "tool_calls", None)
329
+
330
+ if tool_calls:
331
+ for call in tool_calls:
332
+ trace.append(
333
+ {
334
+ "type": "tool_call",
335
+ "name": call.get("name", "Unknown Tool"),
336
+ "args": call.get("args", {}),
337
+ }
338
+ )
339
+ elif last_message.content:
340
+ trace.append(
341
+ {
342
+ "type": "agent_message",
343
+ "content": last_message.content,
344
+ }
345
+ )
346
+ final_answer = last_message.content
347
+
348
+ elif isinstance(last_message, ToolMessage):
349
+ trace.append(
350
+ {
351
+ "type": "tool_result",
352
+ "name": getattr(last_message, "name", "Tool"),
353
+ "content": last_message.content,
354
+ }
355
+ )
356
+
357
+ final_state = graph.get_state(config)
358
+ final_message = final_state.values["messages"][-1]
359
+ if isinstance(final_message, AIMessage) and final_message.content:
360
+ final_answer = final_message.content
361
+
362
+ return {
363
+ "final_answer": final_answer,
364
+ "trace": trace,
365
+ "chunk_count": chunk_count,
366
+ "thread_id": thread_id,
367
+ }
368
+
369
+
370
+ def display_trace(trace: List[Dict[str, Any]]):
371
+ if not trace:
372
+ st.info("No trace available yet.")
373
+ return
374
+
375
+ for i, item in enumerate(trace, 1):
376
+ if item["type"] == "tool_call":
377
+ with st.expander(f"Step {i}: Agent called tool β†’ {item['name']}", expanded=True):
378
+ st.json(item["args"])
379
+
380
+ elif item["type"] == "tool_result":
381
+ with st.expander(f"Step {i}: Tool result ← {item['name']}", expanded=False):
382
+ st.write(item["content"])
383
+
384
+ elif item["type"] == "agent_message":
385
+ with st.expander(f"Step {i}: Agent response", expanded=False):
386
+ st.write(item["content"])
387
+
388
+
389
+ st.title("βš–οΈ Legal Agentic AI Project")
390
+ st.caption("LangGraph ReAct Agent + RAG + Web Search + LLM Reasoning | Hugging Face Spaces Deployment")
391
+
392
+ with st.sidebar:
393
+ st.header("Configuration")
394
+
395
+ model_name = st.selectbox(
396
+ "OpenAI Model",
397
+ ["gpt-4o-mini", "gpt-4o", "gpt-4.1-mini"],
398
+ index=0,
399
+ )
400
+
401
+ temperature = st.slider(
402
+ "Temperature",
403
+ min_value=0.0,
404
+ max_value=1.0,
405
+ value=0.0,
406
+ step=0.1,
407
+ )
408
+
409
+ st.divider()
410
+
411
+ st.subheader("Secrets Status")
412
+ if os.getenv("OPENAI_API_KEY"):
413
+ st.success("OPENAI_API_KEY found")
414
+ else:
415
+ st.error("OPENAI_API_KEY missing")
416
+
417
+ if os.getenv("TAVILY_API_KEY"):
418
+ st.success("TAVILY_API_KEY found")
419
+ else:
420
+ st.warning("TAVILY_API_KEY missing - web search will be skipped")
421
+
422
+ st.divider()
423
+
424
+ st.markdown(
425
+ """
426
+ **Agent Tools**
427
+ 1. RAG Search Tool
428
+ 2. Tavily Web Search Tool
429
+ 3. Loophole Analysis Tool
430
+ """
431
+ )
432
+
433
+
434
+ tab_demo, tab_architecture, tab_code, tab_deployment = st.tabs(
435
+ ["πŸš€ Live Demo", "🧠 Architecture", "🧩 Code Walkthrough", "☁️ HF Deployment"]
436
+ )
437
+
438
+
439
+ with tab_demo:
440
+ st.subheader("Run the Legal Agent")
441
+
442
+ st.markdown(
443
+ """
444
+ This demo takes a legal case, searches an internal legal knowledge base,
445
+ optionally searches the web using Tavily, analyzes loopholes, and produces a final legal analysis.
446
+ """
447
+ )
448
+
449
+ case_text = st.text_area(
450
+ "Legal Case Input",
451
+ value=SAMPLE_CASE,
452
+ height=360,
453
+ )
454
+
455
+ col1, col2 = st.columns([1, 2])
456
+
457
+ with col1:
458
+ run_button = st.button("Run Legal Agent", type="primary", use_container_width=True)
459
+
460
+ with col2:
461
+ st.info("For learners: watch the trace below to understand Observe β†’ Reason β†’ Tool Use β†’ Final Answer.")
462
+
463
+ if run_button:
464
+ if not secrets_ready():
465
+ st.error("OPENAI_API_KEY is missing. Add it in Hugging Face Space β†’ Settings β†’ Repository secrets.")
466
+ elif not case_text.strip():
467
+ st.error("Please enter a legal case.")
468
+ else:
469
+ with st.spinner("Agent is analyzing the case..."):
470
+ try:
471
+ result = run_legal_analysis(case_text, model_name, temperature)
472
+ st.session_state["last_result"] = result
473
+ except Exception as e:
474
+ st.exception(e)
475
+
476
+ if "last_result" in st.session_state:
477
+ result = st.session_state["last_result"]
478
+
479
+ st.success(f"Analysis complete. RAG initialized with {result['chunk_count']} document chunks.")
480
+
481
+ st.markdown("## Final Legal Analysis")
482
+ st.write(result["final_answer"])
483
+
484
+ st.markdown("## Agent Execution Trace")
485
+ display_trace(result["trace"])
486
+
487
+
488
+ with tab_architecture:
489
+ st.subheader("How the Agent Works")
490
+
491
+ st.markdown(
492
+ """
493
+ The notebook project has been converted into a deployable Streamlit app.
494
+
495
+ The core design is a **ReAct Agent** built using **LangGraph**.
496
+
497
+ **Flow:**
498
+
499
+ ```text
500
+ User Case
501
+ ↓
502
+ Agent Node
503
+ ↓
504
+ Decide: Need tools?
505
+ ↓
506
+ Tool Node
507
+ β”œβ”€β”€ RAG Search Tool
508
+ β”œβ”€β”€ Tavily Web Search Tool
509
+ └── Loophole Analysis Tool
510
+ ↓
511
+ Agent Node again
512
+ ↓
513
+ Final Legal Analysis
514
+ ```
515
+ """
516
+ )
517
+
518
+ st.markdown("### What each tool does")
519
+
520
+ st.table(
521
+ [
522
+ {
523
+ "Tool": "rag_search_tool",
524
+ "Purpose": "Searches internal legal knowledge base for precedents.",
525
+ "Example": "Force majeure notice requirement",
526
+ },
527
+ {
528
+ "Tool": "tavily_web_search_tool",
529
+ "Purpose": "Searches current web information using Tavily.",
530
+ "Example": "Recent force majeure legal developments",
531
+ },
532
+ {
533
+ "Tool": "analyze_loopholes_tool",
534
+ "Purpose": "Uses LLM reasoning to identify loopholes and weaknesses.",
535
+ "Example": "Procedural gaps, evidentiary issues, damages weakness",
536
+ },
537
+ ]
538
+ )
539
+
540
+ st.markdown("### Teaching point")
541
+ st.info(
542
+ "This is not just a chatbot. It is an agent because it can reason, decide which tool to use, call tools, observe results, and then continue reasoning."
543
+ )
544
+
545
+
546
+ with tab_code:
547
+ st.subheader("Code Walkthrough for Learners")
548
+
549
+ st.markdown("### 1. State")
550
+ st.code(
551
+ '''
552
+ class AgentState(TypedDict):
553
+ messages: Annotated[list, add_messages]
554
+ case_text: str
555
+ final_analysis: str
556
+ ''',
557
+ language="python",
558
+ )
559
+
560
+ st.markdown("### 2. Tools")
561
+ st.code(
562
+ '''
563
+ tools = [
564
+ rag_search_tool,
565
+ tavily_web_search_tool,
566
+ analyze_loopholes_tool
567
+ ]
568
+ ''',
569
+ language="python",
570
+ )
571
+
572
+ st.markdown("### 3. Agent Node")
573
+ st.code(
574
+ '''
575
+ def agent_node(state):
576
+ system_prompt = SystemMessage(content="Legal analysis instructions...")
577
+ llm_with_tools = llm.bind_tools(tools)
578
+ response = llm_with_tools.invoke([system_prompt] + state["messages"])
579
+ return {"messages": [response]}
580
+ ''',
581
+ language="python",
582
+ )
583
+
584
+ st.markdown("### 4. Conditional Routing")
585
+ st.code(
586
+ '''
587
+ def should_continue(state):
588
+ last_message = state["messages"][-1]
589
+
590
+ if last_message.tool_calls:
591
+ return "tools"
592
+
593
+ return "end"
594
+ ''',
595
+ language="python",
596
+ )
597
+
598
+ st.markdown("### 5. LangGraph Workflow")
599
+ st.code(
600
+ '''
601
+ workflow = StateGraph(AgentState)
602
+ workflow.add_node("agent", agent_node)
603
+ workflow.add_node("tools", ToolNode(tools))
604
+
605
+ workflow.set_entry_point("agent")
606
+ workflow.add_conditional_edges("agent", should_continue, {
607
+ "tools": "tools",
608
+ "end": END
609
  })
610
+ workflow.add_edge("tools", "agent")
611
+
612
+ graph = workflow.compile(checkpointer=MemorySaver())
613
+ ''',
614
+ language="python",
615
+ )
616
+
617
+
618
+ with tab_deployment:
619
+ st.subheader("Hugging Face Spaces Deployment")
620
+
621
+ st.markdown(
622
+ """
623
+ Your Space should have this structure:
624
+
625
+ ```text
626
+ Hands-On-Agentic-Project/
627
+ β”‚
628
+ β”œβ”€β”€ app.py
629
+ β”œβ”€β”€ Dockerfile
630
+ β”œβ”€β”€ requirements.txt
631
+ β”œβ”€β”€ README.md
632
+ β”‚
633
+ └── src/
634
+ └── streamlit_app.py
635
+ ```
636
+
637
+ **Secrets required:**
638
+
639
+ ```text
640
+ OPENAI_API_KEY
641
+ TAVILY_API_KEY
642
+ ```
643
+
644
+ `OPENAI_API_KEY` is required.
645
+ `TAVILY_API_KEY` is optional but recommended for the web-search tool.
646
+
647
+ After uploading this file inside the `src` folder, run:
648
+
649
+ **Factory rebuild** in Hugging Face Spaces.
650
+ """
651
+ )
652
 
653
+ st.warning(
654
+ "This app is for educational demonstration. It is not legal advice and should not be used as a substitute for a qualified legal professional."
655
+ )