Integrate tool routing, memory retrieval, RAG citation, prompt-injection checks, bounded execution, and safe fallback into a single guarded agent loop.
Full problem description visible. Upgrade to unlock the editor, test cases, and solution.
Implement run_guarded_agent(query, tools, memory, knowledge_base, max_steps) that runs a guarded ReAct-style loop with integrated retrieval and safety checks.
Parameters:
- query (str): the user's question.
- tools (dict): tool name to callable mapping.
- memory (dict): a {"get": callable, "put": callable} interface for persistent facts.
- knowledge_base (dict): a {"search": callable} interface returning list of {"content": str, "source": str} dicts.
- max_steps (int): maximum loop iterations.
- llm (callable): the language model to call with the scratchpad on each step.
Requirements:
- Check the query for prompt injection patterns before starting the loop. If detected, return an immediate safe fallback.
- Retrieve relevant knowledge from knowledge_base.search(query) and inject it as context.
- Retrieve relevant facts from memory.get() and merge with knowledge context.
- Run a ReAct loop (up to max_steps) with Final Answer / Action parsing, tool dispatch, and observation collection.
- After each tool observation, call memory.put(fact) to store any factual observation.
- Support a special cite action: Action: cite(source, text) adds an inline citation.
- Return {"answer": str, "citations": list[dict], "steps_used": int, "injection_blocked": bool}.
₹999/monthLimited period launch pricing.
Get the full problem statement, test cases, interactive editor, solution explanation, and visual diagram.
import re
INJECTION_PATTERNS = [
"ignore previous instructions",
"forget your instructions",
"you are now a free",
]
ACTION_RE = re.compile(r"Action:\s*(\w+)\((.*)\)")
FINAL_RE = re.compile(r"Final Answer:\s*(.*)")
CITE_RE = re.compile(r"Action:\s*cite\((.*?),(.*)\)")
def run_guarded_agent(query, tools, memory, knowledge_base, max_steps, llm):
# Prompt injection check
lower_q = query.lower()
for pat in INJECTION_PATTERNS:
if pat in lower_q:
return {"answer": "I cannot process this request.",
"citations": [], "steps_used": 0,
"injection_blocked": True}
# Retrieve knowledge and memory
docs = knowledge_base["search"](query)
context = "\n".join(f"[Source: {d['source']}] {d['content']}" for d in docs)
stored = memory["get"]()
scratchpad = f"Question: {query}\nContext:\n{context}\nMemory:\n{stored}\n"
citations = []
steps = 0Implement guarded loop with cite action and memory storage
return {"answer": "I could not find an answer.", "citations": citations,
"steps_used": steps, "injection_blocked": False}Already have Pro access? Sign in