Here’s an expanded version of Lesson 5.4: Connecting to SQL or Notion for Business Data as part of Module 5: Integrating External APIs and Data Sources.
🗄️ Lesson 5.4: Connecting to SQL or Notion for Business Data
🎯 Lesson Objective
By the end of this lesson, you will be able to:
-
Connect your AI agent to external data sources such as SQL databases and Notion workspaces
-
Query business data directly from these sources during conversations
-
Integrate data retrieval with your AI agent to provide dynamic, context-aware responses
-
Understand best practices for secure, efficient data connections
🔎 Why Connect to SQL or Notion?
-
Many businesses store key data in SQL databases (PostgreSQL, MySQL, SQLite, etc.) or productivity tools like Notion.
-
Integrating these data sources allows your AI agent to:
-
Answer queries with real-time business data
-
Retrieve, update, or summarize information dynamically
-
Automate tasks using internal knowledge without manual intervention
-
Provide personalized responses based on live data
-
🛠️ Tools and Libraries
| Tool / Library | Purpose |
|---|---|
SQLAlchemy / psycopg2 |
Python libraries for SQL database connectivity |
notion-client |
Official Notion API client for Python |
LangChain |
Framework to create tools connecting APIs and models |
Pandas |
Data manipulation and querying (optional) |
🛠️ Step-by-Step: Connecting to SQL Database
✅ Step 1: Setup Database Connection
Using SQLAlchemy for generic SQL support:
from sqlalchemy import create_engine, text
# Example: PostgreSQL connection string format
DATABASE_URL = "postgresql://username:password@localhost:5432/mydatabase"
engine = create_engine(DATABASE_URL)
✅ Step 2: Create a Query Function
def query_sql_database(query: str):
with engine.connect() as connection:
result = connection.execute(text(query))
# Convert results to list of dicts
rows = [dict(row) for row in result]
return rows
✅ Step 3: Create a LangChain Tool
from langchain.tools import Tool
def sql_tool(query: str):
try:
rows = query_sql_database(query)
if not rows:
return "No results found."
# Format output as readable text
return "n".join(str(row) for row in rows)
except Exception as e:
return f"SQL error: {str(e)}"
tools = [
Tool(
name="SQLQueryTool",
func=sql_tool,
description="Executes SQL queries against the business database and returns results"
)
]
✅ Step 4: Use in Your Agent
from langchain.agents import initialize_agent, AgentType
from langchain.llms import Ollama # or OpenAI
llm = Ollama(model="mistral")
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
# Example:
agent.run("Show me the top 5 customers by sales this month.")
🛠️ Step-by-Step: Connecting to Notion API
✅ Step 1: Setup Notion Integration and Get API Key
-
Create an integration at https://www.notion.so/my-integrations
-
Get the Internal Integration Token
-
Share required pages or databases with this integration in Notion
✅ Step 2: Install Notion Client
pip install notion-client
✅ Step 3: Initialize Notion Client
from notion_client import Client
NOTION_TOKEN = "secret_xxx"
notion = Client(auth=NOTION_TOKEN)
DATABASE_ID = "your-database-id"
✅ Step 4: Query Notion Database
def query_notion_database(filter_params=None):
response = notion.databases.query(
**{
"database_id": DATABASE_ID,
"filter": filter_params or {},
"page_size": 10
}
)
results = response.get("results", [])
# Extract properties in a readable format
formatted = []
for page in results:
props = page["properties"]
# Customize this depending on your database schema
formatted.append({k: v.get("title", [{"text": {"content": ""}}])[0]["text"]["content"]
if v["type"] == "title" else str(v.get(v["type"], "")) for k, v in props.items()})
return formatted
✅ Step 5: Create a LangChain Tool for Notion
def notion_tool(query: str):
# Example: parse query or just return latest data
try:
data = query_notion_database()
if not data:
return "No data found in Notion."
return "n".join(str(item) for item in data)
except Exception as e:
return f"Notion API error: {str(e)}"
tools.append(
Tool(
name="NotionDataTool",
func=notion_tool,
description="Fetches and returns business data from Notion databases"
)
)
✅ Step 6: Test Notion Queries in Agent
# Re-initialize or update your agent with new tools list
agent = initialize_agent(
tools=tools,
llm=llm,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True
)
agent.run("Show me the latest projects listed in Notion.")
🔐 Security & Best Practices
| Practice | Reason |
|---|---|
| Use environment variables | Avoid hardcoding credentials in code |
| Limit database permissions | Give read-only access where possible |
| Validate and sanitize queries | Prevent SQL injection attacks |
| Use Notion rate limits wisely | Avoid API throttling |
| Log queries and errors | Monitor and troubleshoot |
💡 Business Use Cases
| Scenario | Description |
|---|---|
| Sales Dashboard Queries | Get live sales, top customers, revenue trends |
| Project Management | Retrieve project statuses from Notion |
| Inventory Checks | Query SQL stock levels and reorder alerts |
| Employee Directory | Fetch team details and contact info from Notion |
✅ Summary
| Step | Outcome |
|---|---|
| Connected to SQL database | Dynamic querying of business data |
| Accessed Notion via API | Retrieve structured workspace content |
| Created LangChain tools | Tools for seamless data access by AI |
| Integrated tools with agent | AI can answer data-driven business questions |
| Followed security best practices | Safe and scalable solution |
69
