larrysim commited on
Commit
1327852
Β·
verified Β·
1 Parent(s): e53a01e

Update app.py

Browse files

fix agent error

Files changed (1) hide show
  1. app.py +16 -25
app.py CHANGED
@@ -28,7 +28,8 @@ try:
28
  from langchain_community.callbacks import StreamlitCallbackHandler
29
  from langchain_community.document_loaders import PyPDFLoader
30
  from langchain_text_splitters import CharacterTextSplitter
31
- from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
 
32
  from langchain_core.runnables import RunnablePassthrough
33
  from langchain_core.output_parsers import StrOutputParser
34
  from langchain_core.tools import tool
@@ -146,11 +147,9 @@ def update_metrics(placeholder):
146
  with st.sidebar:
147
  st.header("πŸ” Authentication")
148
 
149
- # Initialize Session State for Key
150
  if 'is_key_valid' not in st.session_state:
151
  st.session_state['is_key_valid'] = False
152
 
153
- # MANUAL ENTRY ONLY (No Secret Check)
154
  if not st.session_state['is_key_valid']:
155
  api_key_input = st.text_input("Enter Groq API Key", type="password", key="input_key")
156
  if st.button("Validate API Key"):
@@ -211,7 +210,6 @@ if st.session_state.get('is_key_valid', False):
211
  # --- RAG SETUP ---
212
  @st.cache_resource
213
  def setup_rag():
214
- # Check global variable here
215
  if pdfs_missing:
216
  st.error(f"Missing PDFs: {pdfs_missing}")
217
  st.stop()
@@ -251,7 +249,7 @@ if st.session_state.get('is_key_valid', False):
251
 
252
  tools = [get_credit_score, get_account_status, check_pr_status, consult_policy_doc]
253
 
254
- # --- PROMPT TEMPLATE (Steps Enforcement) ---
255
  template = """You are a Loan Risk Officer. You must execute the loan assessment process in exactly 4 sequential steps.
256
 
257
  TOOLS AVAILABLE:
@@ -293,7 +291,12 @@ if st.session_state.get('is_key_valid', False):
293
  Question: {input}
294
  Thought:{agent_scratchpad}"""
295
 
296
- prompt = ChatPromptTemplate.from_template(template)
 
 
 
 
 
297
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)
298
 
299
  col1, col2 = st.columns([1, 2])
@@ -320,26 +323,14 @@ if st.session_state.get('is_key_valid', False):
320
  1. DO NOT query 'get_credit_score' or 'account_status' for Score/Status.
321
  2. USE: Score: {sim_score}, Status: {sim_status}
322
  3. Query 'get_account_status' ONLY for Name/Nationality.
323
- 4. Consult Policy Docs for risk/rates.
324
- 5. Provide a Final Recommendation Report that MUST include:
325
- - Customer Name, ID, Email
326
- - Risk Level, Interest Rate
327
- - Final Decision (Approve/Reject)
328
- - Justification for Decision (Cite specific PDF policies)
329
- - Format in a clear markdown table.
330
  """
331
  else:
332
  query = f"""
333
  Process Loan for Customer ID: {uid}.
334
  1. Query SQL tools for Name, Email, Nationality, Status, Score.
335
  2. IF Nationality is 'Singaporean', SKIP 'check_pr_status'.
336
- 3. Consult Policy Docs for risk/rates.
337
- 4. Provide a Final Recommendation Report that MUST include:
338
- - Customer Name, ID, Email
339
- - Risk Level, Interest Rate
340
- - Final Decision (Approve/Reject)
341
- - Justification for Decision (Cite specific PDF policies)
342
- - Format in a clear markdown table.
343
  """
344
 
345
  with st.status("πŸ€– Agent is processing...", expanded=True) as status:
@@ -358,6 +349,11 @@ if st.session_state.get('is_key_valid', False):
358
  st.success("### πŸ“‹ Final Recommendation")
359
  st.markdown(res['output'])
360
 
 
 
 
 
 
361
  if not use_simulation:
362
  st.divider()
363
  with st.expander("βœ‰οΈ Draft Email"):
@@ -365,11 +361,6 @@ if st.session_state.get('is_key_valid', False):
365
  with st.spinner("Drafting..."):
366
  email_draft = llm.invoke(email_prompt).content
367
  st.text_area("Email Draft", value=email_draft, height=200)
368
-
369
- with st.expander("πŸ” Detailed Trace"):
370
- steps = res.get("intermediate_steps", [])
371
- for i, (action, observation) in enumerate(steps):
372
- st.markdown(f"**Step {i+1}:** Tool `{action.tool}` | Output: `{observation}`")
373
 
374
  elif not st.session_state.get('is_key_valid', False):
375
  st.info("πŸ‘ˆ Please validate your Groq API Key.")
 
28
  from langchain_community.callbacks import StreamlitCallbackHandler
29
  from langchain_community.document_loaders import PyPDFLoader
30
  from langchain_text_splitters import CharacterTextSplitter
31
+ # Added PromptTemplate explicitly here
32
+ from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder, PromptTemplate
33
  from langchain_core.runnables import RunnablePassthrough
34
  from langchain_core.output_parsers import StrOutputParser
35
  from langchain_core.tools import tool
 
147
  with st.sidebar:
148
  st.header("πŸ” Authentication")
149
 
 
150
  if 'is_key_valid' not in st.session_state:
151
  st.session_state['is_key_valid'] = False
152
 
 
153
  if not st.session_state['is_key_valid']:
154
  api_key_input = st.text_input("Enter Groq API Key", type="password", key="input_key")
155
  if st.button("Validate API Key"):
 
210
  # --- RAG SETUP ---
211
  @st.cache_resource
212
  def setup_rag():
 
213
  if pdfs_missing:
214
  st.error(f"Missing PDFs: {pdfs_missing}")
215
  st.stop()
 
249
 
250
  tools = [get_credit_score, get_account_status, check_pr_status, consult_policy_doc]
251
 
252
+ # --- DEFINING THE STRICT STEP-BY-STEP PROMPT ---
253
  template = """You are a Loan Risk Officer. You must execute the loan assessment process in exactly 4 sequential steps.
254
 
255
  TOOLS AVAILABLE:
 
291
  Question: {input}
292
  Thought:{agent_scratchpad}"""
293
 
294
+ prompt = PromptTemplate.from_template(template)
295
+
296
+ # --- CREATING THE AGENT (THE MISSING STEP) ---
297
+ agent = create_tool_calling_agent(llm, tools, prompt)
298
+
299
+ # --- CREATING THE EXECUTOR ---
300
  agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, return_intermediate_steps=True)
301
 
302
  col1, col2 = st.columns([1, 2])
 
323
  1. DO NOT query 'get_credit_score' or 'account_status' for Score/Status.
324
  2. USE: Score: {sim_score}, Status: {sim_status}
325
  3. Query 'get_account_status' ONLY for Name/Nationality.
326
+ 4. Follow the 4-step process and Output Final Report in the specified format.
 
 
 
 
 
 
327
  """
328
  else:
329
  query = f"""
330
  Process Loan for Customer ID: {uid}.
331
  1. Query SQL tools for Name, Email, Nationality, Status, Score.
332
  2. IF Nationality is 'Singaporean', SKIP 'check_pr_status'.
333
+ 3. Follow the 4-step process and Output Final Report in the specified format.
 
 
 
 
 
 
334
  """
335
 
336
  with st.status("πŸ€– Agent is processing...", expanded=True) as status:
 
349
  st.success("### πŸ“‹ Final Recommendation")
350
  st.markdown(res['output'])
351
 
352
+ with st.expander("πŸ” Detailed Trace"):
353
+ steps = res.get("intermediate_steps", [])
354
+ for i, (action, observation) in enumerate(steps):
355
+ st.markdown(f"**Step {i+1}:** Tool `{action.tool}` | Output: `{observation}`")
356
+
357
  if not use_simulation:
358
  st.divider()
359
  with st.expander("βœ‰οΈ Draft Email"):
 
361
  with st.spinner("Drafting..."):
362
  email_draft = llm.invoke(email_prompt).content
363
  st.text_area("Email Draft", value=email_draft, height=200)
 
 
 
 
 
364
 
365
  elif not st.session_state.get('is_key_valid', False):
366
  st.info("πŸ‘ˆ Please validate your Groq API Key.")