---
title: "Turn Any Database Table into an AI Tool: Introducing pxt.retrieval_udf()"
date: "2024-12-20"
author: "Pixeltable Team"
tags:
  - Retrieval UDF
  - Structured Data
  - AI Tools
  - Database Integration
  - AI Agents
  - Enterprise AI
  - Data Access
  - Natural Language
  - AI Functions
  - Production AI
description: "Bridge the gap between structured data and AI agents. Learn how Pixeltable's retrieval_udf() transforms database tables into AI-queryable tools with natural language access to enterprise data."
url: "https://pixeltable.com/blog/retrieval-udf-database-ai-tool"
---

# Turn Any Database Table into an AI Tool: Introducing pxt.retrieval_udf()

## The Problem: AI Meets Structured Enterprise Data

 

 Large Language Models excel at reasoning over unstructured text, but struggle when they need access to structured, tabular data. Traditional [RAG systems](/blog/production-rag-data-centric) work well with documents and embeddings, but what happens when your [AI agent](/blog/practical-guide-building-agents) needs to:
 

 

 - **Look up customer information by ID** from your CRM database

 - **Query product catalogs** with specific filters and availability

 - **Access financial records** based on date ranges and categories

 - **Retrieve inventory data** by location, SKU, and real-time status

 

 

 Until now, you'd need complex custom APIs, manual data formatting, or fragile [pipeline orchestration](/blog/ai-functions-vs-pipelines). **Not anymore.**
 

 
## Introducing pxt.retrieval_udf(): Database Tables as AI Tools

 

 Pixeltable's new `retrieval_udf()` function transforms any data table into an **AI-queryable tool** with just one line of code. Your LLMs can now directly query **structured enterprise data** using natural language, while maintaining the precision and performance of native database operations.
 

 

 This breakthrough bridges the gap between [AI infrastructure](/blog/unified-multimodal-ai-infrastructure-pixeltable) and enterprise data systems, enabling true **AI-native data access** without compromising on security or performance.
 

 
## How It Works: Three Simple Steps

 
The magic of turning **database tables into AI tools** happens in three simple steps:

 
### Step 1: Create Your Data Table

 
```python

import pixeltable as pxt

# Create a customer database with structured data
customers = pxt.create_table('customers', {
 'customer_id': pxt.String, 
 'name': pxt.String, 
 'email': pxt.String,
 'sales': pxt.Int,
 'region': pxt.String
})

# Populate with enterprise data
customers.insert([
 {'customer_id': 'Q371A', 'name': 'Aaron Siegel', 'email': 'aaron@example.com', 'sales': 50000, 'region': 'West'},
 {'customer_id': 'B117F', 'name': 'Marcel Kornacker', 'email': 'marcel@example.com', 'sales': 75000, 'region': 'East'},
 {'customer_id': 'C892D', 'name': 'Sarah Chen', 'email': 'sarah@example.com', 'sales': 92000, 'region': 'West'}
])
 
```

 
### Step 2: Convert Table to AI Tool

 
```python

# Transform any database table into an AI-queryable tool
customer_lookup = pxt.retrieval_udf(
 customers,
 name='get_customer_info', # Tool name for the LLM
 parameters=['customer_id'], # Which columns LLM can query by
 description='Look up customer information by ID', # Optional description
 limit=10 # Max results to return for performance
)
 
```

 
**That's it!** Your database table is now an **AI tool** that any LLM can use.

 
### Step 3: Use with Any LLM Provider

 
```python

from pixeltable.functions.openai import chat_completions, invoke_tools

# Register the database tool for AI access
tools = pxt.tools(customer_lookup)

# Create an AI agent table for queries
agent = pxt.create_table('customer_queries', {'question': pxt.String})

# Set up the declarative AI workflow
agent.add_computed_column(
 llm_response=chat_completions(
 model='gpt-4o-mini',
 messages=[{'role': 'user', 'content': agent.question}],
 tools=tools # LLM automatically gets access to your database
 )
)

agent.add_computed_column(
 results=invoke_tools(tools, agent.llm_response)
)

# Ask natural language questions about your data
agent.insert(question='What is the email address for customer Q371A?')
agent.insert(question='Show me information for customer B117F')

# The AI automatically calls your tool and retrieves the data!
results = agent.select(agent.question, agent.results).collect()
 
```

 
## Real-World Use Cases for AI Database Integration

 
### 1. Intelligent Customer Support Agent

 
Build **AI customer support** that can instantly access customer records, order history, and account details:

 
```python

# Support tickets with automatic customer data lookup
support_tickets = pxt.create_table('tickets', {
 'ticket_id': pxt.String,
 'customer_inquiry': pxt.String
})

# AI agent can look up customer data while responding
customer_tool = pxt.retrieval_udf(customers, parameters=['customer_id', 'email'])
tools = pxt.tools(customer_tool)

support_tickets.add_computed_column(
 response=chat_completions(
 model='gpt-4o',
 messages=[{
 'role': 'system', 
 'content': 'You are a helpful customer support agent. Use the customer lookup tool when needed.'
 }, {
 'role': 'user', 
 'content': support_tickets.customer_inquiry
 }],
 tools=tools
 )
)
 
```

 
### 2. E-commerce Product Assistant

 
Create intelligent shopping assistants that can query your entire product catalog:

 
```python

# Product catalog with real inventory data
products = pxt.create_table('products', {
 'sku': pxt.String,
 'name': pxt.String,
 'category': pxt.String,
 'price': pxt.Float,
 'in_stock': pxt.Bool
})

# AI shopping assistant with database access
product_tool = pxt.retrieval_udf(
 products, 
 name='find_products',
 parameters=['category', 'in_stock'], # Filter by category and availability
 limit=5
)

shopping_agent = pxt.create_table('shopping_queries', {'question': pxt.String})
tools = pxt.tools(product_tool)

# Natural language: "Show me available electronics under $500"
# AI automatically queries your product database!
 
```

 
### 3. Financial Data Analysis Agent

 
Build financial analysts that can access market data, trading records, and portfolio information:

 
```python

# Market data with time-series information
stocks = pxt.create_table('market_data', {
 'symbol': pxt.String,
 'sector': pxt.String,
 'price': pxt.Float,
 'volume': pxt.Int,
 'date': pxt.Timestamp
})

# Financial analyst AI with database access
market_tool = pxt.retrieval_udf(
 stocks,
 name='get_stock_data',
 parameters=['symbol', 'sector'],
 description='Retrieve current stock information and trading data'
)

# AI can now answer: "What's the current price of AAPL?" or "Show me tech stocks with high volume"
 
```

 
## Advanced Features for Enterprise AI

 
### Custom Parameters and Security Controls

 
You have precise control over which database columns your **AI agents** can access, ensuring **enterprise security**:

 
```python

# Only allow querying by specific, safe fields
restricted_lookup = pxt.retrieval_udf(
 customers,
 parameters=['region'], # AI can only filter by region, not sensitive fields
 limit=20
)

# Or use all non-computed columns (default behavior)
full_lookup = pxt.retrieval_udf(customers) # Uses all data columns responsibly
 
```

 
### Multiple Data Sources in One Agent

 
Combine multiple **database tables** into a comprehensive AI system:

 
```python

# Combine multiple enterprise data sources
customer_tool = pxt.retrieval_udf(customers, parameters=['customer_id'])
product_tool = pxt.retrieval_udf(products, parameters=['sku', 'category'])
order_tool = pxt.retrieval_udf(orders, parameters=['customer_id', 'status'])

# Register all database tools for AI access
tools = pxt.tools(customer_tool, product_tool, order_tool)

# AI can now access customer data, products, AND orders in one conversation
# "Show me all pending orders for customer Q371A along with product details"
 
```

 
## Technical Benefits for Production AI Systems

 
### 🚀 Performance Advantages

 

 - **Direct database queries** with no embedding computation overhead

 - **Efficient filtering** using native SQL operations and indexes

 - **Configurable result limits** for optimal response times

 - **Native pagination** for large datasets

 

 
### 🔒 Enterprise Security

 

 - **Built-in parameter validation** prevents malformed queries

 - **Controlled access** through specified parameters only

 - **No raw SQL injection risks** - queries are parameterized and safe

 - **Fine-grained permissions** at the column level

 

 
### 🔄 Integration Flexibility

 

 - **Works with any LLM provider** (OpenAI, Anthropic, [Gemini](/blog/working-with-gemini), local models)

 - **Supports all data types** (strings, numbers, timestamps, JSON, multimodal)

 - **Automatic type checking** and intelligent conversion

 - **Seamless integration** with existing [Pixeltable workflows](/blog/declarative-multimodal-incremental)

 

 
### 📈 Production Scalability

 

 - **Optimized query engine** leveraging Pixeltable's performance

 - **Handles large datasets** efficiently with intelligent caching

 - **Persistent and versioned** data storage for reliability

 - **Built-in observability** for debugging and monitoring

 

 
## Beyond Basic Retrieval: Hybrid AI Systems

 

 `retrieval_udf()` integrates seamlessly with Pixeltable's broader **AI infrastructure capabilities**, enabling sophisticated hybrid systems that combine multiple AI approaches:
 

 
```python

# Combine structured retrieval with vector similarity search
documents = pxt.create_table('docs', {
 'id': pxt.String,
 'content': pxt.String,
 'category': pxt.String,
 'embedding': pxt.Array[pxt.Float] # Vector embeddings for semantic search
})

# Traditional semantic search with embeddings
semantic_results = documents.order_by(
 documents.embedding.cosine_similarity(query_embedding)
).limit(5)

# Plus structured lookup by ID and metadata
doc_tool = pxt.retrieval_udf(documents, parameters=['id', 'category'])

# Best of both worlds: semantic + structured retrieval in one AI system
tools = pxt.tools(doc_tool, other_enterprise_tools)
 
```

 

 This **hybrid approach** is particularly powerful for [enterprise RAG systems](/blog/embedding-management-guide) where you need both semantic understanding and precise data retrieval.
 

 
## Getting Started with AI Database Integration

 
Ready to give your **AI agents** native access to structured data? Here's the minimal setup:

 
```bash

# Install Pixeltable with AI functions
pip install pixeltable

# For OpenAI integration
pip install pixeltable[openai]

# For other providers
pip install pixeltable[anthropic] # or [gemini], [together], etc.
 
```

 
```python

# Basic example: Database → AI Tool → Intelligent Agent
import pixeltable as pxt
from pixeltable.functions.openai import chat_completions, invoke_tools

# Your existing data → AI tool → Production-ready agent
# Just three lines of declarative setup!
data_table = pxt.get_table('your_existing_table')
ai_tool = pxt.retrieval_udf(data_table, parameters=['key_column'])
tools = pxt.tools(ai_tool)
 
```

 
## The Future of Enterprise AI-Data Integration

 

 `pxt.retrieval_udf()` represents a fundamental shift in how **AI systems interact with enterprise data**. Instead of forcing structured data into unstructured formats or building complex API layers, we're giving **AI models native access** to the databases they need to query.
 

 

 This approach aligns with Pixeltable's vision of [declarative AI infrastructure](/blog/declarative-multimodal-incremental), where data access becomes as simple and powerful as SQL was for traditional applications.
 

 
### This Opens Up Possibilities For:

 

 - **Hybrid RAG systems** combining semantic search with precise database queries

 - **Agentic workflows** that can access any enterprise system transparently

 - **Real-time AI applications** that work with live, changing operational data

 - **Precise enterprise retrieval** without semantic search approximations when exactness matters

 - **Multi-modal AI systems** that query both unstructured content and structured records

 

 
## Frequently Asked Questions About AI Database Integration

 
 
 
 What is pxt.retrieval_udf() and how does it work?
 
 

 
 
 
 
 `pxt.retrieval_udf()` is a Pixeltable function that converts any database table into an AI-queryable tool. It creates a bridge between LLMs and structured data, allowing AI agents to query databases using natural language while maintaining the performance and security of native database operations.

 
 
 
 
 
 
 How is this different from traditional RAG systems?
 
 

 
 
 
 
 Traditional RAG systems use vector embeddings for semantic search over unstructured documents. `retrieval_udf()` enables direct, precise queries over structured data like customer records, product catalogs, and financial data. You can combine both approaches for powerful hybrid AI systems.

 
 
 
 
 
 
 Is it secure for enterprise data access?
 
 

 
 
 
 
 Yes! You control exactly which columns AI agents can query through the `parameters` argument. All queries are parameterized to prevent SQL injection. The tool only accesses data through the specific parameters you define, ensuring enterprise-grade security.

 
 
 
 
 
 
 Which LLM providers work with retrieval_udf()?
 
 

 
 
 
 
 All major LLM providers work with `retrieval_udf()`, including OpenAI, Anthropic's Claude, Google's Gemini, Together AI, and local models. The tool integration follows OpenAI's function calling standard, making it universally compatible.

 
 
 
 
 
 
 How does performance compare to custom APIs?
 
 

 
 
 
 
 Performance is often superior because `retrieval_udf()` uses Pixeltable's optimized query engine with native SQL operations, intelligent caching, and efficient result limits. There's no overhead from embedding computation, and queries benefit from database indexes and optimizations.

 
 
 
 
 
 
 Can I combine multiple database tables in one AI agent?
 
 

 
 
 
 
 Absolutely! You can create multiple `retrieval_udf()` tools from different tables and register them all with `pxt.tools()`. The AI agent will automatically choose the appropriate tool based on the user's query, enabling access to your entire enterprise data ecosystem.

 
 
 
 

 
## Related Resources & Next Steps

 

 - [AI Agent Architecture: A Practical Guide](/blog/practical-guide-building-agents)

 - [Production RAG Systems: Data-Centric Approach](/blog/production-rag-data-centric)

 - [AI Functions vs. Pipelines: The Declarative Approach](/blog/ai-functions-vs-pipelines)

 - [Unified Multimodal AI Infrastructure](/blog/unified-multimodal-ai-infrastructure-pixeltable)

 - [Embedding Management for Production RAG](/blog/embedding-management-guide)

 - [Pixeltable Functions API Documentation](https://docs.pixeltable.com/api/functions)

 - [AI Tools Examples and Tutorials](https://docs.pixeltable.com/examples/tools)

 

 
## Start Building AI-Native Data Applications

 
Ready to bridge the gap between your **enterprise databases** and **AI agents**? Get started today:

 

 - **Install Pixeltable:** `pip install pixeltable`

 - **Try the Playground:** [Interactive Pixeltable Playground](https://pixeltable.com/playground)

 - **Follow the Quick Start:** [10-Minute Quick Start Guide](https://docs.pixeltable.com/overview/quick-start)

 - **Join the Community:** [Pixeltable Discord](https://discord.com/invite/QPyqFYx2UN)

 - **Star on GitHub:** [github.com/pixeltable/pixeltable](https://github.com/pixeltable/pixeltable)

 

 
*Transform your databases into AI-native infrastructure. Let your agents query data as naturally as humans do.* 🚀