Building Tool-Calling AI Agents with LangChain, LangGraph, Gemini and PostgreSQL | AI Engineering Series #5

Welcome to Part 5 of my AI Engineering Series!

In the previous articles, we built an intelligent AI workflow, added persistent conversation memory, implemented conversational RAG and improved document retrieval using hybrid search.

In this article, we will take our application one step further by building an AI agent that can interact with tools, retrieve live database information and perform actions with human approval.

1. What Is an AI Agent?

An AI agent is a system that uses a language model to understand requests, select appropriate tools, execute actions and generate responses based on the results.

Unlike a traditional chatbot, an AI agent can interact with databases, APIs and external systems.

For example:

  • Retrieve employee information.
  • Calculate available leave balances.
  • Search enterprise documents.
  • Create IT support tickets.
  • Retrieve existing support tickets.

2. What Are We Building?

We are extending our AI Smart Assistant into an enterprise tool-calling AI agent.

Our application will support:

  • Intelligent tool selection.
  • Multi-step tool execution.
  • PostgreSQL employee information.
  • Live leave balance retrieval.
  • RAG-based company policy search.
  • Support ticket management.
  • Human-in-the-loop approval.
  • Persistent agent memory.
  • Duplicate-ticket protection.
  • FastAPI endpoints.

3. Technology Stack

Technology Purpose
Python Application development
FastAPI REST APIs
LangChain Tool definitions and LLM integration
LangGraph Agent orchestration
Gemini Reasoning and tool selection
PostgreSQL Employee data, tickets and checkpoints
ChromaDB Document vector storage
BM25 Keyword retrieval
Psycopg PostgreSQL connectivity
Pydantic API validation

We will reuse the technologies and configurations from our previous articles.

4. Understanding the Agent Architecture

flowchart TD A[User Request] --> B[FastAPI] B --> C[Gemini Agent] C --> D{Tool Required?} D -->|No| E[Final Response] D -->|Read Tool| F[ToolNode] D -->|Write Tool| G[Human Approval] G -->|Approved| F G -->|Rejected| H[Cancel Action] F --> I[PostgreSQL] F --> J[ChromaDB] F --> C C -. Checkpoints .-> I

The agent decides which tools are required. LangGraph controls their execution and routes sensitive write operations through an approval node.

5. Understanding Tool Calling

Tool calling allows a language model to request the execution of a predefined function.

For example, when a user asks:

Multiply 125 by 48.

Gemini can generate a structured tool call:

{ "name": "calculator", "args": { "first_number": 125, "second_number": 48, "operation": "multiply" } } 

The application executes the function and returns its result to the language model.

The model does not directly execute the Python function.

6. Verify Required Dependencies

Activate the existing Python virtual environment.

Verify that LangChain and LangGraph tool-calling components are available:

python -c "from langchain_core.tools import tool; from langgraph.prebuilt import ToolNode; print('Agent dependencies available')" 

We will reuse our existing Gemini model configuration, PostgreSQL connection pool and document retrieval implementation.

7. Create Calculator and Date-Time Tools

File: app/tools.py

Create a new file.

from datetime import datetime, timezone from langchain_core.tools import tool @tool def calculator( first_number: float, second_number: float, operation: str ) -> str: """Perform addition, subtraction, multiplication or division.""" if operation == "add": return str(first_number + second_number) if operation == "subtract": return str(first_number - second_number) if operation == "multiply": return str(first_number * second_number) if operation == "divide": if second_number == 0: return "Error: Cannot divide by zero." return str(first_number / second_number) return "Error: Unsupported operation." @tool def get_current_datetime() -> str: """Return the current date and time in UTC.""" return datetime.now(timezone.utc).isoformat() 

The @tool decorator converts Python functions into tools that can be exposed to a language model.

Test the calculator:

python -c "from app.tools import calculator; print(calculator.invoke({'first_number':100,'second_number':25,'operation':'multiply'}))" 

Expected output:

2500.0 

8. Create the PostgreSQL Employees Table

Open pgAdmin and select our existing ai_smart_assistant database.

Execute:

CREATE TABLE IF NOT EXISTS employees ( employee_id VARCHAR(20) PRIMARY KEY, name VARCHAR(100) NOT NULL, department VARCHAR(100) NOT NULL, designation VARCHAR(100) NOT NULL, annual_leave_balance INTEGER NOT NULL DEFAULT 24, sick_leave_balance INTEGER NOT NULL DEFAULT 12, casual_leave_balance INTEGER NOT NULL DEFAULT 6, is_active BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, CHECK (annual_leave_balance >= 0), CHECK (sick_leave_balance >= 0), CHECK (casual_leave_balance >= 0) ); 

This table stores employee information and available leave balances.

9. Insert Employee Records

Insert fictional employee records for testing.

INSERT INTO employees ( employee_id, name, department, designation, annual_leave_balance, sick_leave_balance, casual_leave_balance ) VALUES ( 'EMP001', 'Arjun Kumar', 'Engineering', 'Software Engineer', 18, 10, 4 ), ( 'EMP002', 'Priya Sharma', 'Human Resources', 'HR Manager', 15, 8, 3 ), ( 'EMP003', 'Rahul Reddy', 'IT Support', 'Support Engineer', 20, 12, 5 ) ON CONFLICT (employee_id) DO NOTHING; 

Verify the records:

SELECT * FROM employees; 

Our agent will retrieve employee information directly from PostgreSQL.

10. Configure PostgreSQL Dictionary Responses

File: app/database.py

Update the existing connection pool configuration.

Add the import:

from psycopg.rows import dict_row 

Update the pool:

pool = ConnectionPool( conninfo=DB_URI, min_size=1, max_size=10, open=False, kwargs={ "autocommit": True, "prepare_threshold": 0, "row_factory": dict_row } ) 

The dict_row configuration allows us to access database results using column names.

For example:

employee["employee_id"] employee["name"] 

Without this configuration, Psycopg normally returns tuples.

11. Create the Employee Service

File: app/employee_service.py

Create a new file.

from app.database import pool def find_employee(employee_id: str): employee_id = employee_id.strip().upper() with pool.connection() as connection: with connection.cursor() as cursor: cursor.execute( """ SELECT employee_id, name, department, designation, annual_leave_balance, sick_leave_balance, casual_leave_balance FROM employees WHERE employee_id = %s AND is_active = TRUE """, (employee_id,) ) employee = cursor.fetchone() return employee 

We are using parameterized SQL queries instead of constructing SQL statements from user input.

This service retrieves current employee information from PostgreSQL.

12. Create Employee and Leave Balance Tools

File: app/tools.py

Add the following import:

from app.employee_service import find_employee 

Append the following tools:

@tool def get_employee_details(employee_id: str) -> dict: """Retrieve employee details using an employee ID.""" employee = find_employee(employee_id) if not employee: return { "status": "error", "message": "Employee not found" } return { "status": "success", "employee_id": employee["employee_id"], "name": employee["name"], "department": employee["department"], "designation": employee["designation"] } @tool def get_leave_balance(employee_id: str) -> dict: """Retrieve available leave balances for an employee.""" employee = find_employee(employee_id) if not employee: return { "status": "error", "message": "Employee not found" } return { "status": "success", "employee_id": employee["employee_id"], "name": employee["name"], "annual_leave": employee["annual_leave_balance"], "sick_leave": employee["sick_leave_balance"], "casual_leave": employee["casual_leave_balance"] } 

The agent can now retrieve live employee information and leave balances.

13. Convert RAG Retrieval into an Agent Tool

File: app/tools.py

Reuse the hybrid retrieval implementation from Part 4.

Add:

from app.retriever import retrieve_documents 

Append:

@tool def search_company_documents(question: str) -> dict: """Search company policies, benefits and enterprise documents.""" documents = retrieve_documents( question=question, strategy="hybrid", k=3 ) if not documents: return { "status": "not_found", "documents": [] } return { "status": "success", "documents": [ { "content": doc.page_content, "file_name": doc.metadata.get("source"), "page_number": doc.metadata.get("page_number") } for doc in documents ] } 

Instead of building another RAG pipeline, we expose our existing retrieval system as an agent tool.

The agent can combine company policies with live employee information.

14. Create the Support Tickets Table

Execute the following SQL in PostgreSQL:

CREATE TABLE IF NOT EXISTS support_tickets ( ticket_id BIGSERIAL PRIMARY KEY, employee_id VARCHAR(20) NOT NULL REFERENCES employees(employee_id), subject VARCHAR(200) NOT NULL, description TEXT NOT NULL, priority VARCHAR(20) NOT NULL DEFAULT 'medium', status VARCHAR(20) NOT NULL DEFAULT 'open', request_id VARCHAR(255) UNIQUE, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, CHECK (priority IN ('low', 'medium', 'high')) ); 

The employee ID establishes a relationship between employees and support tickets.

The unique request ID helps prevent duplicate records when the same tool call is replayed.

If you already have a support tickets table, add the missing column and unique index through a database migration rather than recreating the table.

15. Create the Support Ticket Service

File: app/ticket_service.py

Create a new file.

from app.database import pool from app.employee_service import find_employee def create_ticket( employee_id: str, subject: str, description: str, priority: str = "medium", request_id: str | None = None ): employee_id = employee_id.strip().upper() priority = priority.strip().lower() subject = subject.strip() description = description.strip() if not find_employee(employee_id): return { "status": "error", "message": "Employee not found" } if priority not in ["low", "medium", "high"]: return { "status": "error", "message": "Invalid priority" } if not subject or len(subject) > 200: return { "status": "error", "message": "Invalid ticket subject" } if not description: return { "status": "error", "message": "Description is required" } with pool.connection() as connection: with connection.cursor() as cursor: cursor.execute( """ INSERT INTO support_tickets ( employee_id, subject, description, priority, request_id ) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (request_id) DO UPDATE SET request_id = EXCLUDED.request_id RETURNING ticket_id """, ( employee_id, subject, description, priority, request_id ) ) result = cursor.fetchone() return { "status": "success", "ticket_id": result["ticket_id"], "employee_id": employee_id, "subject": subject, "priority": priority, "message": "Support ticket created successfully" } def get_ticket(ticket_id: int): with pool.connection() as connection: with connection.cursor() as cursor: cursor.execute( """ SELECT * FROM support_tickets WHERE ticket_id = %s """, (ticket_id,) ) result = cursor.fetchone() if not result: return { "status": "error", "message": "Ticket not found" } result["created_at"] = ( result["created_at"].isoformat() ) return { "status": "success", "ticket": result } 

The service validates input, creates support tickets and retrieves existing records.

The request ID protects against replaying the same tool call. It does not prevent separate requests from creating similar tickets.

16. Create Support Ticket Tools

File: app/tools.py

Add the imports:

from typing import Annotated, Literal from langchain_core.tools import InjectedToolCallId from app.ticket_service import create_ticket, get_ticket 

Append:

@tool def create_support_ticket( employee_id: str, subject: str, description: str, tool_call_id: Annotated[str, InjectedToolCallId], priority: Literal["low", "medium", "high"] = "medium" ) -> dict: """Create an IT support ticket after human approval.""" return create_ticket( employee_id=employee_id, subject=subject, description=description, priority=priority, request_id=tool_call_id ) @tool def get_support_ticket(ticket_id: int) -> dict: """Retrieve support ticket details using its ticket ID.""" return get_ticket(ticket_id) 

LangGraph injects the tool call ID during execution.

The model does not need to generate this identifier as a tool argument.

17. Understand Human-in-the-Loop Approval

AI agents should not automatically execute every action.

Read operations, such as retrieving employee information, can execute directly in this learning application.

Write operations, such as creating support tickets, require explicit user approval.

LangGraph provides:

  • interrupt() to pause execution.
  • Command(resume=...) to resume execution.
  • Checkpointers to persist execution state.

Our approval mechanism is enforced through graph routing rather than relying only on prompt instructions.

18. Create the Human Approval Node

File: app/approval.py

Create a new file.

from langgraph.types import interrupt from langchain_core.messages import ToolMessage from langgraph.graph import MessagesState def approval_node(state: MessagesState): last_message = state["messages"][-1] tool_calls = last_message.tool_calls decision = interrupt({ "type": "tool_approval", "message": "Approve the proposed tool execution?", "tool_calls": tool_calls }) if decision is True: return {} return { "messages": [ ToolMessage( content="Tool execution rejected by user.", tool_call_id=call["id"] ) for call in tool_calls ] } 

When a write operation is requested, execution pauses before the tool runs.

If the user rejects the request, the proposed operations are cancelled.

For simplicity, approval applies to the entire proposed tool-call batch when it contains a write operation.

19. Build the LangGraph Agent Workflow

File: app/agent.py

Create the agent workflow.

from langgraph.graph import ( StateGraph, MessagesState, START, END ) from langgraph.prebuilt import ToolNode from langchain_core.messages import ( SystemMessage, ToolMessage ) from app.llm import llm from app.graph import memory from app.approval import approval_node from app.tools import ( calculator, get_current_datetime, get_employee_details, get_leave_balance, search_company_documents, create_support_ticket, get_support_ticket ) agent_tools = [ calculator, get_current_datetime, get_employee_details, get_leave_balance, search_company_documents, create_support_ticket, get_support_ticket ] agent_llm = llm.bind_tools(agent_tools) WRITE_TOOLS = { "create_support_ticket" } def call_agent(state:Source:https://dev.to/jayakrishna_chadalawada/building-tool-calling-ai-agents-with-langchain-langgraph-gemini-and-postgresql-ai-engineering-159a

Related posts