Lecture: 7, Agentic RAG and Autonomous Systems Duration: 45 minutes Difficulty: Advanced
| Requirement | How to Check |
|---|---|
| Python 3.10+ | python --version |
| Dependencies | pip install openai rich python-dotenv |
| LLM access | Ollama or DeepSeek API key |
cd lab_06_agent
python lab_06_agent.py
| File | Description |
|---|---|
lab_06_agent.py |
Main script with ReAct loop and TODO section |
setup_db.py |
Creates the hospital SQLite database |
solutions.py |
Tool execution solution |
data/hospital.db |
Auto-generated database (patients, labs, prescriptions) |
Read the SYSTEM_PROMPT in lab_06_agent.py. Notice how we force the LLM to output specific prefixes (Thought:, Action:, Action Input:, Observation:). This structured output is what allows our Python code to parse the LLM’s intent and run the correct tool.
Find the TODO: YOUR CODE HERE section in the run_agent() function.
You need to map the parsed action string to the actual Python function (get_database_schema or execute_sql_query), run it with the action_input, and store the result in the observation variable.
Run the script and watch the terminal. You will see the agent’s internal monologue:
get_database_schema.execute_sql_query.Final Answer.Ask the agent complex questions that require JOINs:
User Question: What is the most common gender among our patients?
--- Step 1 ---
Thought: I need to know the database schema to find the table that stores patient genders.
Action: get_database_schema
Action Input: None
Observation: CREATE TABLE patients (subject_id INTEGER PRIMARY KEY, gender TEXT NOT NULL...)
--- Step 2 ---
Thought: The 'patients' table has a 'gender' column. I will query the count of each gender.
Action: execute_sql_query
Action Input: SELECT gender, COUNT(*) FROM patients GROUP BY gender ORDER BY COUNT(*) DESC LIMIT 1
Observation: Columns: gender, COUNT(*)
('M', 6)
--- Step 3 ---
Thought: The query returned 'M' (Male) with a count of 6.
Final Answer: The most common gender among patients is Male.
| Issue | Solution |
|---|---|
Tool execution not implemented! |
You must complete the TODO in Task 2. |
| Agent gets stuck in a loop | Sometimes local models struggle with ReAct parsing. Try using the DeepSeek API mode. |
| Infinite loops | The max_steps parameter prevents the agent from running forever. |