How to Intermediate · 3 min read

How to give AI agent database access

Quick answer
To give an AI agent database access, implement a secure API or direct database connection that the agent can query dynamically. Use code to connect the agent to the database via libraries like psycopg2 for PostgreSQL or sqlite3, and ensure queries are sanitized to prevent injection.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0
  • Database access credentials
  • pip install psycopg2-binary or sqlite3 (built-in)

Setup

Install necessary Python packages and set environment variables for API keys and database credentials.

  • Use pip install openai psycopg2-binary for PostgreSQL or sqlite3 is built-in.
  • Set environment variables for OPENAI_API_KEY and database connection info.
bash
pip install openai psycopg2-binary

Step by step

This example shows how to connect an AI agent to a PostgreSQL database, run a query, and use the result in an AI prompt.

python
import os
import psycopg2
from openai import OpenAI

# Connect to PostgreSQL database
conn = psycopg2.connect(
    dbname=os.environ['DB_NAME'],
    user=os.environ['DB_USER'],
    password=os.environ['DB_PASSWORD'],
    host=os.environ['DB_HOST'],
    port=os.environ.get('DB_PORT', 5432)
)
cur = conn.cursor()

# Query example
cur.execute("SELECT name, price FROM products WHERE id = %s", (1,))
product = cur.fetchone()

# Prepare prompt with database data
prompt = f"Product info: Name={product[0]}, Price=${product[1]}. Suggest a marketing tagline."

# Initialize OpenAI client
client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print(response.choices[0].message.content)

# Cleanup
cur.close()
conn.close()
output
Innovative and affordable, the ProductName is your perfect choice for quality and value!

Common variations

You can adapt this pattern for other databases like SQLite or MySQL by changing the connection library and query syntax. Async database clients and streaming AI responses are also possible.

python
import os
import sqlite3
from openai import OpenAI

# SQLite connection
conn = sqlite3.connect('example.db')
cur = conn.cursor()

cur.execute("SELECT name, price FROM products WHERE id = ?", (1,))
product = cur.fetchone()

prompt = f"Product info: Name={product[0]}, Price=${product[1]}. Suggest a marketing tagline."

client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": prompt}]
)

print(response.choices[0].message.content)

cur.close()
conn.close()
output
Discover the unbeatable value of ProductName — quality meets affordability!

Troubleshooting

  • If you get connection errors, verify your database credentials and network access.
  • For query errors, check SQL syntax and parameterization to avoid injection.
  • If AI responses are irrelevant, ensure the prompt includes clear context from the database.

Key Takeaways

  • Use parameterized queries to securely fetch data for AI prompts.
  • Connect AI agents to databases via APIs or direct DB clients depending on architecture.
  • Always sanitize inputs and handle credentials securely using environment variables.
Verified 2026-04 · gpt-4o
Verify ↗